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

Viewed 117

I have a test.jl Julia script file in a directory, e.g., /home/directory1. Assume that I want to save the output of this code as a .txt file in the same directory. My problem is that, obviously, the .txt file will be saved in the working directory of Julia, which by pwd() is somewhere else, e.g., /home/julia/.

I wonder how can I change the working directory in the test.jl script WITHOUT writting the directory address, /home/directory1 , manually? I know that I can change the working directory by cd("/home/directory1"), but the problem is that I don't want to write the address manually. Is there any way to get the directory address of test.jl within itself by a command?

1 Answers

You can get that information using macro @__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.

Example:

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
Related