英文:
How do you determine the full path of the currently running executable in go?
问题
我一直在OSX上使用这个函数:
// 获取当前可执行文件路径的快捷方式
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
}
...但它非常混乱,并且在Windows上根本不起作用,尤其是在git-bash上也不行。
有没有一种跨平台的方法来实现这个?
注意:具体来说,args[0]取决于二进制文件的调用方式;在某些情况下,它只是二进制文件本身,例如"app"或"app.exe";所以你不能只使用它。
英文:
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.
答案1
得分: 4
这是我认为在任何平台下都能正常工作的传统方法。
import (
"fmt"
"os"
"path/filepath"
)
// 获取当前可执行文件的路径的快捷方式
func ExecPath() string {
var here = os.Args[0]
here, err := filepath.Abs(here)
if err != nil {
fmt.Printf("奇怪的路径:%s\n", err)
}
return here
}
英文:
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
}
答案2
得分: 0
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())
}
英文:
I don't think there is a cross-platform way to do this.
However, on OS X, there is a better way. dyld provides a function _NSGetExecutablePath()
that gives you the path to the executable. You can call this with 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())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论