Reputation: 53
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
Upvotes: 1
Views: 242
Reputation: 28126
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
.
Upvotes: 3
Reputation: 91409
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)
Upvotes: 1