英文:
How can I find out the installation directory of the running program in Go?
问题
如何编写一个名为demo.go
的程序,该程序打印出demo.exe
的安装路径?
D:\>go build demo.go
demo.exe
在D:\
中。将demo.exe
移动到C:\Windows
后,在D:\
路径下(不在C:\Windows
中)运行demo.exe
应该打印出C:\Windows
。
下面的图片显示了这种情况下不起作用的原因(因为demo.exe总是获取其当前执行路径,而不是其真实路径)。它只告诉你当前的执行目录,而不是包含该文件的目录。
https://github.com/axgle/go/blob/master/may_app_path_bug.jpg
更新:Windows/Linux解决方案在这里 https://github.com/axgle/app
英文:
How can I write a demo.go
program that prints the installation path of demo.exe
?
D:\>go build demo.go
demo.exe
is in D:\
. After moving demo.exe
to C:\Windows
,then under the D:\
path(it is Not in the C:\Windows
) running demo.exe
should print C:\Windows
.
below picture showing than is not working for this case(because demo.exe always get its current execute path,NOT its really path) . That just tells you the current execute directory, not the directory containing the file
https://github.com/axgle/go/blob/master/may_app_path_bug.jpg
Update: window/linux solution is here https://github.com/axgle/app
答案1
得分: 3
package main
import (
"fmt"
"path/filepath"
"os"
)
func main() {
path, err := filepath.Abs(os.Args[0])
if err != nil { panic(err) }
fmt.Println(path)
}
通过阅读os.Args
和filepath.Abs
了解更多信息。
英文:
package main
import (
"fmt"
"path/filepath"
"os"
)
func main() {
path, err := filepath.Abs(os.Args[0])
if err != nil { panic(err) }
fmt.Println(path)
}
Learn more by reading about os.Args
and filepath.Abs
.
答案2
得分: 1
一个可以尝试的起点是:
package main
import "os"
func main() {
println(os.Args[0])
}
$ go run main.go
/tmp/go-build135649844/command-line-arguments/_obj/a.out
$
(仅在Linux上进行了测试,但os包应该是跨平台的,如果可能的话)
英文:
One may try to start from e.g.:
package main
import "os"
func main() {
println(os.Args[0])
}
$ go run main.go
/tmp/go-build135649844/command-line-arguments/_obj/a.out
$
(Tested on Linux only, but the os package should be cross platform where/if possible)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论