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)

猜你喜欢

转载自blog.csdn.net/wzb_wzt/article/details/107565071