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

huangapple go评论100阅读模式
英文:

What's the best way to get the path of the executable during runtime?

问题

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

在Python中,这将是变量:

os.path.realpath(__file__)
英文:

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__)

答案1

得分: 3

这可能与C语言中的情况相同,换句话说,没有一种可移植且百分之百可靠的方法。请参考https://stackoverflow.com/questions/933850/how-to-find-the-location-of-the-executable-in-c/933996#933996。

英文:

It's probably the same as in C, in other words, there isn't a portable fool-proof method. See https://stackoverflow.com/questions/933850/how-to-find-the-location-of-the-executable-in-c/933996#933996

答案2

得分: 2

一个快速的解决方案(不一定是通用的)是由Andrew Brookins在“Go:如何获取当前文件的目录”中提出的:

> 我最终发现了runtime.Caller()
它返回当前goroutine堆栈的一些细节,包括文件路径。

> 我的问题是在一个共享包中打开一个数据文件。
我想出的解决方案是:

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

One quick fix in go (not necessary a universal one) is proposed by Andrew Brookins 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"))

答案3

得分: -2

我找到的最好的方法是使用os.Getwd()。请参阅此处的文档:golang doc

英文:

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

huangapple
  • 本文由 发表于 2010年5月12日 05:31:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/2814606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定