golang获取此文件的绝对路径?

获取当前文件的绝对路径,哪怕是被其他程序调用,也是获取当前文件的绝对路径,怎么做呢?
因为我要用crontab去执行一个golang文件,我要获取golang文件当前的路径,而不是/root路径,
比如说我的golang位于/app/scripts/gosrc/main.go,我想在任意位置执行golang程序都能获得这个路径

阅读 9.4k
4 个回答

获取源文件路径,可以用 runtime.Caller

func Caller(skip int) (pc uintptr, file string, line int, ok bool)
Caller reports file and line number information about function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to ascend, with 0 identifying the caller of Caller. (For historical reasons the meaning of skip differs between Caller and Callers.) The return values report the program counter, file name, and line number within the file of the corresponding call. The boolean ok is false if it was not possible to recover the information.

=========================================

os.Executable

Executable returns the path name for the executable that started the current process. There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, path/filepath.EvalSymlinks might help.

Executable returns an absolute path unless an error occurred.

The main use case is finding resources located relative to an executable.

Executable is not supported on nacl.

得到启动当前进程的可执行文件的路径与文件名。

_, file, line, ok = runtime.Caller(calldepth)

file对应的是全路径名称, line行数

calldepth int类型填 0123

例子:
func Test() {

Test1()

}

func Test1() {

Test2()

}

func Test2() {

_, file, line, ok = runtime.Caller(calldepth)

}

这边的calldepth填012就分别对应了Test2 Test1 Test中的对应调用地方

golang程序启动的时候第一个参数就是程序所在路径的绝对路径,一般用os.Args[0]来获取。
根据这个路径你可以计算出程序运行所在的绝对目录了。

你这么做其实是不对的做法,
即使 go run main.go 看似是在运行main文件,但其实

go run main.go = go build main.go -o main + ./main

他都是二进制文件了,你获取到源文件其实是没有任何意义的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题