【问题标题】:What's the best way to get the path of the executable during runtime?在运行时获取可执行文件路径的最佳方法是什么?
【发布时间】:2010-05-11 21:31:11
【问题描述】:

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

在 python 中,这将是变量:

os.path.realpath(__file__)

【问题讨论】:

  • 这假定可执行文件有一个路径......

标签: go


【解决方案1】:

这可能和 C 中的一样,换句话说,没有可移植的万无一失的方法。见How do I find the location of the executable in C?

【讨论】:

    【解决方案2】:

    Andrew Brookins 在“Go: How to Get the Directory of the Current File”中提出了一个快速修复(不一定是通用的):

    我最终发现了runtime.Caller()
    这将返回有关当前 goroutine 堆栈的一些详细信息,包括文件路径。

    我的问题是在共享包中打开一个数据文件。
    我做的是:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 工作目录不一定是包含可执行文件的目录。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多