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

How to get the address of a Julia script file within itself?

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

我想知道如何在不手动写入目录地址 /home/directory1 的情况下更改 test.jl 脚本中的工作目录?我知道我可以通过 cd("/home/directory1") 更改工作目录,但问题是我不想手动写入地址。有什么方法可以通过命令获取test.jl自身的目录地址吗?

您可以使用宏 @__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.

示例:

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