如何获取 Julia 脚本文件本身的地址?

CLA*_*UDE 4 julia

test.jl我的目录中有一个Julia 脚本文件,例如/home/directory1. 假设我想将此代码的输出保存为.txt同一目录中的文件。我的问题是,显然,该.txt文件将保存在 Julia 的工作目录中,该目录位于pwd()其他位置,例如/home/julia/.

我想知道如何更改脚本中的工作目录test.jl而不手动写入目录地址/home/directory1?我知道我可以通过 更改工作目录cd("/home/directory1"),但问题是我不想手动写入地址。有没有办法test.jl通过命令获取其内部的目录地址?

Prz*_*fel 5

您可以使用宏获取该信息@__FILE__

help?> @__FILE__
  @__FILE__ -> AbstractString

  Expand to a string with the path to the file containing the macrocall, or an empty string if evaluated by julia -e <expr>. Return nothing if the macro was missing parser source information. Alternatively see PROGRAM_FILE.
Run Code Online (Sandbox Code Playgroud)

例子:

julia> open("c:\\temp\\some.jl","w") do f
       println(f, "println(\"Running at \$(@__FILE__)\")")
       end

julia> include("c:\\temp\\some.jl")
Running at c:\temp\some.jl

shell> julia "c:\temp\some.jl"
Running at c:\temp\some.jl
Run Code Online (Sandbox Code Playgroud)

  • 更好的是,使用解析为当前文件的_directory_的`@__DIR__`... (4认同)