Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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/directory , 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading