golang獲取當前執行程序的路徑

背景: linux golang
在程序運行中,經常需要讀取文件,如果文件路徑寫成絕對路勁,對於程序移植到其他機器上執行時,可能會出錯,找不到文件。
所以,最好的方式是寫成相對路徑。

實現方式:
假設有如下文件路徑:

test-
     - main.go
     - api
     - - testApi.go
package package
import (
"path"
"runtime"
"fmt"
)
func main () {
   _, filename, _, ok := runtime.Caller(1)
   var cwdPath string
   if ok {
     cwdPath = path.Join(path.Dir(filename), "") // the the main function file directory
   }  else  {
     cwdPath = "./"
   }
fmt.Println("cwd path...", cwdPath )
}

(注意修改package 名字)
以上代碼放在main.go 中時,執行 go run main.go , 輸出 /usr/local/go/src/runtime
以及 上述代碼放在 testApi.go 中時, 依舊執行 go run main.go 輸出 /home/cogoadmin/gopath/src/test

其他
python 中,文件獲取自己所在的路徑

import os
cwd = os.path.dirname(os.path.abspath(__file__))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章