如何获取当前运行文件的目录?

2023-12-27

在nodejs中我使用__目录名 http://nodejs.org/api/globals.html#globals_dirname。 Golang 中与此等效的是什么?

我用谷歌搜索并找到了这篇文章http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/ http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/。他在哪里使用下面的代码

_, filename, _, _ := runtime.Caller(1)
f, err := os.Open(path.Join(path.Dir(filename), "data.csv"))

但这是 Golang 中正确的方式还是惯用的方式呢?


编辑:从 Go 1.8(2017 年 2 月发布)开始,推荐的方法是使用os.Executable https://tip.golang.org/pkg/os/#Executable:

func Executable() (string, error)

可执行文件返回启动当前进程的可执行文件的路径名。无法保证路径仍然指向正确的可执行文件。如果使用符号链接来启动进程,则结果可能是符号链接或其指向的路径,具体取决于操作系统。如果需要稳定的结果,path/filepath.EvalSymlinks 可能会有所帮助。

要仅获取可执行文件的目录,您可以使用path/filepath.Dir https://golang.org/pkg/path/filepath/#Dir.

Example https://play.golang.org/p/_aolLr7uEH:

package main

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

func main() {
    ex, err := os.Executable()
    if err != nil {
        panic(err)
    }
    exPath := filepath.Dir(ex)
    fmt.Println(exPath)
}

旧答案:

你应该能够使用os.Getwd http://golang.org/pkg/os/#Getwd

func Getwd() (pwd string, err error)

Getwd 返回与当前目录相对应的根路径名。如果当前目录可以通过多个路径到达(由于符号链接),Getwd 可能会返回其中任何一个。

例如:

package main

import (
    "fmt"
    "os"
)

func main() {
    pwd, err := os.Getwd()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(pwd)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何获取当前运行文件的目录? 的相关文章

随机推荐