英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论