go 获取文件执行的路径

方法:

path, _ := exec.LookPath(os.Args[0])
fmt.Println(path)  
abs, _ := filepath.Abs(path)
fmt.Println(abs)
index := strings.LastIndex(abs, string(os.PathSeparator))
fmt.Println(path[:index]) 

os.Args是用来获取命令行执行参数分片

  • 当go run 运行时会将文件转移到临时路径下,然后再进行编译和执行,分片0就是C:\Users\xxx\AppData\Local\Temp___go_build_main_go.exe;
  • go build编译执行时,那么分片0为执行文件的相对路径为(main.go)
fmt.Println(os.Args)
//output:[C:\Users\xxx\AppData\Local\Temp\___go_build_main_go.exe]

exec.LookPath()

  • 根据传入的参数来从PATH中获取可执行文件的绝对路径(没有编译的)或者相对路径(编译后的);参数若带分割号就直接查询返回
func LookPath(file string) (string, error)
LookPath searches for an executable named file in the directories named by the 
PATH environment variable. If file contains a slash, it is tried directly and the
PATH is not consulted. LookPath also uses PATHEXT environment variable to match a 
suitable candidate. The result may be an absolute path or a path relative to the 
current directory.

filepath.Abs()

  • 根据传入的路径计算出绝对路径,如果传入的为相对路径,那么它会把当前路径拼接上
  • 编译后返回的是真实的路径(D:\go_project\src\github.com\wzbwzt\studyGo\GetPath\main.exe)
  • 未编译执行返回的是临时执行路径
    (C:\Users\xxx\AppData\Local\Temp___go_build_main_go.exe)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值