英文:
Open a file in the same directory as the .go source file in Go
问题
当在源文件$PWD/dir/src.go中使用
os.Open("myfile.txt")
它会在$PWD中寻找myfile.txt(这看起来很正常)。
有没有办法告诉Go在与src.go相同的目录中寻找myfile.txt?我需要类似于Ruby中的__FILE__
的东西。
英文:
When in a source file $PWD/dir/src.go I use
os.Open("myfile.txt")
it looks for myfile.txt in $PWD (which looks normal).
Is there way to tell Go to look for myfile.txt in the same directory as src.go ? I need something like __FILE__
in Ruby.
答案1
得分: 8
Go不是一种解释性语言,所以在与源文件相同位置查找文件是没有意义的。Go二进制文件是编译的,运行二进制文件时不需要源文件存在。因此,Go没有类似于__FILE__的等效功能。runtime.Caller函数返回的是二进制文件编译时的文件名。
我认为,如果我们了解您为什么需要这个功能,我们可以给出更好的建议。
英文:
Go is not an interpreted language so looking for a file in the same location as the source file doesn't make any sense. The go binary is compiled and the source file doesn't need to be present for the binary to run. Because of that Go doesn't come with an equivalent to FILE. The runtime.Caller function returns the file name at the time the binary was compiled.
I think perhaps if we understood why you actually wanted this functionality we could advise you better.
答案2
得分: 0
一个可能的替代骨架:
func __FILE__() (fn string) {
_, fn, _, _ = runtime.Caller(0)
return
}
详情请参见这里。
英文:
A possible substitute skeleton:
func __FILE__() (fn string) {
_, fn, _, _ = runtime.Caller(0)
return
}
Details here.
答案3
得分: 0
使用包osext
它提供了一个名为ExecutableFolder()
的函数,该函数返回当前运行程序可执行文件所在文件夹的绝对路径(对于cron作业非常有用)。它是跨平台的。
<!-- language: go -->
package main
import (
"github.com/kardianos/osext"
"fmt"
"log"
)
func main() {
folderPath, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
}
fmt.Println(folderPath)
}
您还可以获取完整的可执行文件路径(类似于__FILE__
):
<!-- language: go -->
package main
import (
"github.com/kardianos/osext"
"fmt"
)
func main() {
exeAbsolutePath, _ := osext.Executable()
fmt.Println(exeAbsolutePath)
}
英文:
Use package osext
It's providing function ExecutableFolder()
that returns an absolute path to folder where the currently running program executable reside (useful for cron jobs). It's cross platform.
<!-- language: go -->
package main
import (
"github.com/kardianos/osext"
"fmt"
"log"
)
func main() {
folderPath, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
}
fmt.Println(folderPath)
}
You can also get full executable path (similar to __FILE__
):
<!-- language: go -->
package main
import (
"github.com/kardianos/osext"
"fmt"
)
func main() {
exeAbsolutePath, _ := osext.Executable()
fmt.Println(exeAbsolutePath)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论