Golang
main.go
package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    getExePath()
    getAbsPath()
    getWorkingDirPath()
}

func getExePath() string {
    ex, err := os.Executable()
    if err != nil {
        panic(err)
    }
    exePath := filepath.Dir(ex)
    fmt.Println("exePath:", exePath)
    return exePath
}

func getAbsPath() string {
    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
        panic(err)
    }
    fmt.Println("absPath:", dir)
    return dir
}

func getWorkingDirPath() string {
    dir, err := os.Getwd()
    if err != nil {
        panic(err)
    }
    fmt.Println("workingDirPath:", dir)
    return dir
}

我们可以按以下用例场景运行:

# Go RUN 源码运行
$go run main.go
# 形如 /tmp/go-build****/b***/exe 之类为 `go run` 之后编译的临时目录
exePath: /tmp/go-build854301005/b001/exe
absPath: /tmp/go-build854301005/b001/exe
workingDirPath: /path-to-project/go-path-test/
# 编译后运行二进制文件
$go build -o main main.go
$./main
exePath: /path-to-project/go-path-test
absPath: /path-to-project/go-path-test
workingDirPath: /path-to-project/go-path-test
# 在其它目录下运行二进制文件
$cd ..
$./go-path-test/main
exePath: /path-to-project/go-path-test
absPath: /path-to-project/go-path-test
workingDirPath: /path-to-project
getExePath()getAbsPath()getWorkingDirPath()main
本作品采用《CC 协议》,转载必须注明作者和本文链接