在运行时获取可执行文件路径的最佳方法是什么?

在运行时获取可执行文件路径的最佳方法是什么?

问题描述:

If my go program can be executed in different ways (cron, monit, etc..), what's the most reliable way to get the directory that contains the executable, during runtime?

In python, this would be the variable:

os.path.realpath(__file__)

如果我的go程序可以通过不同的方式(cron,monit等)执行,那是最可靠的 在运行时获取包含可执行文件的目录的方法? p>

在python中,这将是变量: p>

  os.path  .realpath(__ file __)
  code>  pre> 
  div>

It's probably the same as in C, in other words, there isn't a portable fool-proof method. See How do I find the location of the executable in C?

One quick fix in go (not necessary a universal one) is proposed by Andrew *ins in "Go: How to Get the Directory of the Current File":

I eventually found out about runtime.Caller().
This returns a few details about the current goroutine’s stack, including the file path.

The context of my problem was opening a data file in a shared package.
What I cooked up was:

_, filename, _, _ := runtime.Caller(1)
f, err := os.Open(path.Join(path.Dir(filename), "data.csv"))

The best way I found is to use os.Getwd(). See documentation here: golang doc