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

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?