获取 __FILE__ 个已编译脚本

Get __FILE__ of compiled script

如何让我的 Crystal 脚本的编译版本获得它自己的 __FILE__。这是一个例子。我有一个名为 ~/test.cr 的文件,其中包含以下内容:

puts __FILE__

我通过Crystal

编译脚本
~$ crystal ~/test.cr -o ~/test.compiled

接下来我运行~/test.compiled。我产生了结果

/Users/Account1/test.cr

尽管 __FILE__ 实际上是

/Users/Account1/test.compiled

有没有办法让它产生

/Users/Account1/test.compiled

而不是

/Users/Account1/test.cr

元常量__FILE__ 始终指向源文件,而不是可执行文件。但是,您可以使用 [=13=] 获取当前可执行文件路径(或使用 File.expand_path 的完整路径):

foo.cr:

puts [=10=]
puts File.expand_path([=10=])

然后编译执行:

$~ crystal build foo.cr
$~ ./foo
./foo
/Users/MyUser/foo