The macrocall @__FILE__ does not return the directory of the file, but rather the REPL output number

I have been using to following to change my working directory to the location of my .jl scripts in Atom as follows without problems:


When I run a script with this in vs code, I get an error and it doesn’t change my working directory:

julia> cd(dirname(@__FILE__))
ERROR: IOError: chdir : invalid argument (EINVAL)
 [1] uv_error at .\libuv.jl:97 [inlined]
 [2] cd(::String) at .\file.jl:84
 [3] top-level scope at REPL[2]:1

The reason that is I think is because there is nothing in the strong for cd() to work on:

julia> @__FILE__

julia> dirname(@__FILE__)

When I use Alt+Enter to evaluate it inline from within a script, then it works fine. But when I run the actual script I get the error message above.

Any ideas on what is going on?

How are you running the script? It works fine for me:


dir = dirname(@__FILE__)

println("Directory: $dir")


$ julia test.jl 
Directory: /tmp

this is because you’re in REPL and REPL is not a file anywhere

You probably want pwd() instead of dirname(@__FILE__). That will give you the directory you are cded into. As @jling explained, @__FILE__ will always give you the path of the script the macro was expanded in, so it doesn’t give anything useful in the REPL.

Use @__DIR__. When running from a file it’s the same as dirname(@__FILE__) and when running from the REPL it’s the same as pwd().

1 Like

Yes, it appears that is the problem. However the behaviour of Atom and VS Code are different:

Ctrl + Enter when highlighting cd(dirname(@__FILE__)) in Atom does not through up the error, but does in VS Code.

I discovered that if I use Alt + Enter in VS Code when highlighting cd(dirname(@__FILE__)) it works fine.