dongxing4643 2013-04-19 03:46
浏览 86
已采纳

您如何确定go中当前正在运行的可执行文件的完整路径?

I've been using this function on osx:

// Shortcut to get the path to the current executable                      
func ExecPath() string {                                                   
  var here = os.Args[0]                                                    
  if !strings.HasPrefix(here, "/") {                                       
    here, _ = exec.LookPath(os.Args[0])                                    
    if !strings.HasPrefix(here, "/") {                                     
      var wd, _ = os.Getwd()                                               
      here = path.Join(wd, here)                                           
    }                                                                      
  } 
  return here                                                              
}

...but its pretty messy, and it doesn't work on windows at all, and certainly not in git-bash on windows.

Is there a way of doing this cross platform?

NB. Specifically that args[0] depends on how the binary is invoked; it is in some cases only the binary itself, eg. "app" or "app.exe"; so you can't just use that.

  • 写回答

2条回答 默认 最新

  • dousha4804 2013-04-19 08:27
    关注

    This is the traditional way of doing it which I think will work under any platform.

    import (
        "fmt"
        "os"
        "path/filepath"
    )
    
    // Shortcut to get the path to the current executable                      
    func ExecPath() string {
        var here = os.Args[0]
        here, err := filepath.Abs(here)
        if err != nil {
            fmt.Printf("Weird path: %s
    ", err)
        }
        return here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序