Find the path to the executable

后端 未结 3 665
半阙折子戏
半阙折子戏 2020-12-03 10:05

I compile a program with Go for various platforms and run it by calling a relative path or just by its name (if it is in the PATH variable).

Is it possible to find o

相关标签:
3条回答
  • 2020-12-03 10:09

    You can use os.Executable for getting executable path on Go 1.8 or above version.

    import (
        "os"
        "path"
        "log"
    )
    
    func main() {
        ex, err := os.Executable()
        if err != nil { log.Fatal(err) }
        dir := path.Dir(ex)
        log.Print(dir)
    }
    
    0 讨论(0)
  • 2020-12-03 10:10

    Use package osext.

    It's providing function Executable() that returns an absolute path to the current program executable. It's portable between systems.

    Online documentation

    package main
    
    import (
        "github.com/kardianos/osext"
        "fmt"
    )
    
    func main() {
        filename, _ := osext.Executable()
        fmt.Println(filename)
    }
    
    0 讨论(0)
  • 2020-12-03 10:33

    This is not go-specific (unless the go "standard library" contains some function to do it), and there is no portable solution. For solutions on some common platforms, see e.g. How do I find the location of the executable in C? or Finding current executable's path without /proc/self/exe .

    0 讨论(0)
提交回复
热议问题