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__))
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值