= nil { log.Fatalf("Failed to get current executable path: %v", err) } fmt.Println("Current executable path:", path) } 方法二:使用 filepath.Abs 和os.Args[0] 这种方法适用于直接运行源代码文件(如使用 go run 命令)或已编译的可执行文件。 go package main import ( "fmt" "log" "os...
func getCurrentAbPathByExecutable() string { exePath, err := os.Executable() if err != nil { log.Fatal(err) } res, _ := filepath.EvalSymlinks(filepath.Dir(exePath)) return res } 首先通过go run启动 D:\Projects\demo>go run main.go getCurrentAbPathByExecutable = C:\Users\XXX\App...
fmt.Println("getCurrentAbPathByExecutable = ", getCurrentAbPathByExecutable()) } // 获取当前执行程序所在的绝对路径 func getCurrentAbPathByExecutable() string { exePath, err :=os.Executable() if err != nil { log.Fatal(err) } res, _ := filepath.EvalSymlinks(filepath.Dir(exePath)) re...
我意识到,既然go run时可以通过runtime.Caller()获取到正确的结果,go build时也可以通过os.Executable()来获取到正确的路径;那如果我能判定当前程序是通过go run还是go build执行的,选择不同的路径获取方法,所有问题不就迎刃而解了吗。Go没有提供接口来区分程序是go run还是go build执行,但我们...
getCurrentAbPathByExecutable = D:\Projects\demo 1. 2. 通过对比执行结果,我们发现两种执行方式,我们获取到了不同的路径。而且很明显,go run获取到的路径是错误的。 原因:这是由于go run会将源代码编译到系统TEMP或TMP环境变量目录中并启动执行;而go build只会在当前目录编译出可执行文件,并不会自动执行。
GOBINgo的可执行路径,默认位于GOPATH/bin 目录,这个路径决定了你执行go install后的编译文件的安装路径,需要将他加入到你的系统PATH环境变量中; GO111MODULE 这个是用来控制go的运行模式是模块方式还是GOPATH模式; GOARCH系统架构,如 amd64, 386, arm, ppc64 , 这个配置不合适代码直接无法运行; ...
bupafengyu1楼•4 个月前
摘要:golang 可以使用下面的函数获取当前执行程序的路径。 func getCurrentPath() string { if ex, err := os.Executable(); err == nil { return filepath.Dir(ex) } return "./" }阅读全文 posted @2022-05-31 15:04星河赵阅读(2465)评论(0)推荐(0) ...
命令源码文件被安装以后,GOPATH 如果只有一个工作区,那么相应的可执行文件会被存放当前工作区的 bin 文件夹下;如果有多个工作区,就会安装到 GOBIN 指向的目录下。 命令源码文件是 Go 程序的入口。 同一个代码包中最好也不要放多个命令源码文件。多个命令源码文件虽然可以分开单独 go run 运行起来,但是无法通过 ...
Current Time0:00 / Duration-:- Loaded:0% Topics we will coverhide Method-1: The os package and Executable() function Method-2: file/filepath and the Abs() function Method-3: Using the osext package Method-4: Get the source file location ...