简体   繁体   English

如何确定当前运行的可执行文件的完整路径?

[英]How do you determine the full path of the currently running executable in go?

I've been using this function on osx: 我一直在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. ...但它非常混乱,它根本不适用于Windows,当然也不适用于Windows上的git-bash。

Is there a way of doing this cross platform? 有没有办法做这个跨平台?

NB. NB。 Specifically that args[0] depends on how the binary is invoked; 具体来说,args [0]取决于如何调用二进制文件; it is in some cases only the binary itself, eg. 在某些情况下,它只是二进制本身,例如。 "app" or "app.exe"; “app”或“app.exe”; so you can't just use that. 所以你不能只使用它。

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\n", err)
    }
    return here
}

I don't think there is a cross-platform way to do this. 我不认为有一种跨平台的方式来做到这一点。

However, on OS X, there is a better way. 但是,在OS X上,有一种更好的方法。 dyld provides a function _NSGetExecutablePath() that gives you the path to the executable. dyld提供了一个函数_NSGetExecutablePath() ,它为您提供了可执行文件的路径。 You can call this with CGo. 你可以用CGo调用它。

package main

// #import <mach-o/dyld.h>
import "C"

import (
    "fmt"
)

func NSGetExecutablePath() string {
    var buflen C.uint32_t = 1024
    buf := make([]C.char, buflen)

    ret := C._NSGetExecutablePath(&buf[0], &buflen)
    if ret == -1 {
        buf = make([]C.char, buflen)
        C._NSGetExecutablePath(&buf[0], &buflen)
    }
    return C.GoStringN(&buf[0], C.int(buflen))
}

func main() {
    fmt.Println(NSGetExecutablePath())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM