我能够获取当前目录的完整路径,现在我想创建一个函数,该函数将读取或获取执行代码的文件名。我可以获取文件名,但是它返回编写代码的原始文件名:
func GetFileName() string {
_, fpath, _, ok := runtime.Caller(0)
if !ok {
err := errors.New("failed to get filename")
panic(err)
}
filename := filepath.Base(fpath)
// remove extension
filename = removeExtension(filename)
return filename + ".log"
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是获取执行代码的当前文件名,例如:
我创建了app.go
:
package my
function getCurrentFileName() string {
// some code here that will return the filename where this code is executed.
}
Run Code Online (Sandbox Code Playgroud)
然后当我在不同位置(getCurrentFileName()
例如hello.go
在不同位置)中调用不同文件时。它会返回hello.go
。
我在这里停留了一段时间,正在寻找答案。
基本上这就是你告诉/传递给的 runtime.Caller()
:返回条目之前要跳过的堆栈条目数。
如果你通过0
在你的代码,这意味着返回堆栈项,其中runtime.Caller()
被称为(如果你叫runtime.Caller()
)。传递1
将跳过您的函数,并返回调用您的函数的函数:
pc, file, line, ok := runtime.Caller(1)
if ok {
fmt.Printf("Called from %s, line #%d, func: %v\n",
file, line, runtime.FuncForPC(pc).Name())
}
Run Code Online (Sandbox Code Playgroud)
调用包含此功能的subplay.A()
示例(在我的示例中):
7 func main() {
8 // Comment line
9 subplay.A()
10 }
Run Code Online (Sandbox Code Playgroud)
输出:
Called from /home/icza/gows/src/play/play.go, line #9, func: main.main
Run Code Online (Sandbox Code Playgroud)
我们看到代码play.go
从包的函数main()
中打印出在第9行调用了我们的函数的代码main
。