How to get the path of a Julia script

I have found a small inconsistency in the google group lists. When you type “julia get directory of script” into a google search box (finding a way to programmatically determine the file path of the currently executing source code), you get this answer: Redirecting to Google Groups

However, this method fails if you call it from code that gets passed into a macro in another file. I had this problem when I used Base.source_path() in a function that was called from within a testset. However, @FILE does not have this problem. I wanted to suggest this to the user on the google group, but it is locked, so I decided to tell you.

Minimal example of what I mean:

foo.jl:

function foo()
  println(Base.source_path())
end

bar.jl:

include("foo.jl")
using Base.Test
@testset "my_testset" begin
  foo()
end

Anyways, maybe this is the desired behavior of Base.source_path(), but I was confused at the behavior I saw given the description given in the google group.

So, for new julia users directed here from google, to get the path of the currently executing file, you should use @FILE. Somebody please correct me if I’m wrong.

6 Likes

The google group is (was) a mailing list, not documentation. Documentation can be found at http://docs.julialang.org/en/latest/. I think it is possible that you are looking for Base.PROGRAM_FILE.

3 Likes

I understand that the google group was not documentation. However, like stackoverflow, it is actually what curious new users like me find when they google documentation questions. I just wanted to put something on the web on the right forum to correct what I found.

Base.PROGRAM_FILE is not what I want because it does not give the full path, and in fact suffers from the same issue that Base.source_path does when used in a macro. Try it in my example!

3 Likes

Thanks the pointer to @__FILE__ was very useful. (__@DIR__ is also very useful FWIW)

10 Likes

Thank you for the info, very useful.

@__DIR__ (The @ is in the wrong place above.)

8 Likes

Dead link to Base.PROGRAM_FILE, use instead:
https://docs.julialang.org/en/v1/base/constants/#Base.PROGRAM_FILE

1 Like

correct.