如何在Go中找到正在运行的程序的安装目录?

huangapple go评论113阅读模式
英文:

How can I find out the installation directory of the running program in Go?

问题

如何编写一个名为demo.go的程序,该程序打印出demo.exe的安装路径?

  1. D:\>go build demo.go

demo.exeD:\中。将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?

  1. 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.Argsfilepath.Abs了解更多信息。

英文:
  1. package main
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "os"
  6. )
  7. func main() {
  8. path, err := filepath.Abs(os.Args[0])
  9. if err != nil { panic(err) }
  10. fmt.Println(path)
  11. }

Learn more by reading about os.Args and filepath.Abs.

答案2

得分: 1

一个可以尝试的起点是:

  1. package main
  2. import "os"
  3. func main() {
  4. println(os.Args[0])
  5. }

  1. $ go run main.go
  2. /tmp/go-build135649844/command-line-arguments/_obj/a.out
  3. $

(仅在Linux上进行了测试,但os包应该是跨平台的,如果可能的话)

英文:

One may try to start from e.g.:

  1. package main
  2. import "os"
  3. func main() {
  4. println(os.Args[0])
  5. }

  1. $ go run main.go
  2. /tmp/go-build135649844/command-line-arguments/_obj/a.out
  3. $

(Tested on Linux only, but the os package should be cross platform where/if possible)

huangapple
  • 本文由 发表于 2012年5月12日 21:06:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/10564014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定