英文:
Find the path to the executable
问题
我使用Go编译程序,可以在各个平台上通过调用相对路径或者直接使用程序名(如果在PATH变量中)来运行它。
是否有办法找出可执行文件的位置?
比如,我的程序叫做“foo
(.exe
)"。我可以通过./foo
、foo
(如果在PATH中)、../../subdir/subdir/foo
来运行它。
我尝试使用os.Args[0]
,我猜我应该检查程序名是否包含除了“foo”之外的其他内容。如果是,使用filepath.Abs
,如果不是,使用(我找不到函数名,有一个函数可以查找PATH来确定程序的位置)。
英文:
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 out where the executable is?
Say, my program is called "foo
(.exe
)". I can run ./foo
, foo
(if it's in the PATH), ../../subdir/subdir/foo
.
I have tried to use os.Args[0]
and I guess I should check if the program name contains something different besides "foo". If yes, use filepath.Abs
, if no, use (I can't find the function name, there is a function that looks through the PATH to check where the program is).
答案1
得分: 48
你可以在Go 1.8或更高版本中使用os.Executable
来获取可执行文件的路径。
import (
"os"
"path"
"log"
)
func main() {
ex, err := os.Executable()
if err != nil { log.Fatal(err) }
dir := path.Dir(ex)
log.Print(dir)
}
英文:
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)
}
答案2
得分: 46
使用osext包。
它提供了一个名为Executable()
的函数,返回当前程序可执行文件的绝对路径。
它在不同系统之间是可移植的。
<!-- language: go -->
package main
import (
"github.com/kardianos/osext"
"fmt"
)
func main() {
filename, _ := osext.Executable()
fmt.Println(filename)
}
英文:
Use package osext.
It's providing function Executable()
that returns an absolute path to the current program executable.
It's portable between systems.
<!-- language: go -->
package main
import (
"github.com/kardianos/osext"
"fmt"
)
func main() {
filename, _ := osext.Executable()
fmt.Println(filename)
}
答案3
得分: 4
这不是特定于Go的(除非Go的“标准库”中包含某些执行此操作的函数),也没有可移植的解决方案。有关一些常见平台的解决方案,请参见例如https://stackoverflow.com/questions/933850/how-to-find-the-location-of-the-executable-in-c或https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe/1024937#1024937。
英文:
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. https://stackoverflow.com/questions/933850/how-to-find-the-location-of-the-executable-in-c or https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe/1024937#1024937 .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论