mattu
mattu

Reputation: 1024

Julia: find out if run from REPL or command line

Is there a way to determine if a julia script myprog.jl has been invoked from the command line via julia myprog.jl or from the REPL via include("myprog.jl")?

Background: I'm using the ArgParse.jl package and since I cannot pass command line arguments from the REPL, I want to just set a variable ARGS = "argA --optB 1 --flagC" prior to calling include("myprog.jl") in order to achieve the same result as julia myprog.jl argA --optB 1 --flagC from the command line. To do this I need to know if the program was called from the command line or from the REPL, such that I could just write something like

if called_from_repl
    parse_args(split(ARGS),s)
else
    parse_args(s)
end

Upvotes: 4

Views: 1173

Answers (2)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42194

Simply use isinteractive to determine whether Julia is running an interactive session.

Consider the example below (I use $ for command line prompt and julia> for Julia REPL prompt)

$ more test.jl

println("interactive : $(isinteractive())")


$ julia test.jl
interactive : false

Now let us run the same script in the REPL:

julia> include("test.jl")
interactive : true

Upvotes: 10

Maurice van Leeuwen
Maurice van Leeuwen

Reputation: 191

Yes this is possible. Base defines the constant Base.PROGRAM_FILE which contains script name passed on the command line. The macro Base.@__FILE__ evaluates to the path of the script where this macro is called.

The expression abspath(PROGRAM_FILE) == @__FILE__ evaluates to true in the script passed on the command line, but false for included scripts.

This technique is discussed in the Julia Lang documentation: https://docs.julialang.org/en/latest/manual/faq/#man-scripting-1

Upvotes: 2

Related Questions