找到可执行文件的路径 [英] Find the path to the executable
问题描述
我使用Go为各种平台编译程序,并通过调用相对路径或仅通过其名称(如果它位于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).
说我的程序叫做 foo
( .EXE
)。我可以运行 ./ foo
, foo
(如果它在PATH中), .. /../ subdir / subdir / foo
。
Say, my program is called "foo
(.exe
)". I can run ./foo
, foo
(if it's in the PATH), ../../subdir/subdir/foo
.
我试过使用 os.Args [0]
,我想我应该检查程序名是否包含除foo之外的不同内容。如果是,请使用 filepath.Abs
,如果不是,请使用(我找不到函数名称,有一个函数通过PATH来检查程序的位置)。
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).
推荐答案
使用软件包 osext
Use package osext.
它提供了返回当前程序可执行文件绝对路径的函数 Executable()
。
它可以在系统间移植。
It's providing function Executable()
that returns an absolute path to the current program executable.
It's portable between systems.
package main
import (
"github.com/kardianos/osext"
"fmt"
)
func main() {
filename, _ := osext.Executable()
fmt.Println(filename)
}
这篇关于找到可执行文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!