ephemeris
ephemeris

Reputation: 785

Is there a way to run julia script with arguments from REPL?

I can run julia script with arguments from Powershell as > julia test.jl 'a' 'b'. I can run a script from REPL with include("test.jl") but include accepts just one argument - the path to the script.

From playing around with include it seems that it runs a script as a code block with all the variables referencing the current(?) scope so if I explicitly redefine ARGS variable in REPL it catches on and displays corresponding script results:

>ARGS="c","d"
>include("test.jl") # prints its arguments in a loop
c
d

This however gives a warning for redefining ARGS and doesn't seem the intended way of doing that. Is there another way to run a script from REPL (or from another script) while stating its arguments explicitly?

Upvotes: 1

Views: 8417

Answers (3)

Ruffus Goodman
Ruffus Goodman

Reputation: 1

Not sure if it helps, but it took me a while to figure this:

On your path "C:\Users\\.julia\config\" there may be a .jl file called startup.jl

The trick is that not always Julia setup will create this. So, if neither the directory nor the .jl file exists, create them.

Julia will treat this .jl file as a command list to be executed every time you run REPL. It is very handy in order to set the directory of your projects (i.e. C:\MyJuliaProject\MyJuliaScript.jl using cd("")) and frequent used libs (like using Pkg, using LinearAlgebra, etc)

I wanted to share this as I didn't find anyone explicit saying this directory might not exist in your Julia device's installation. It took me more than it should to figure this thing out.

Upvotes: 0

mbauman
mbauman

Reputation: 31362

You probably don't want to run a self-contained script by includeing it. There are two options:

  1. If the script isn't in your control and calling it from the command-line is the canonical interface, just call it in a separate Julia process. run(`$JULIA_HOME/julia path/to/script.jl arg1 arg2`). See running external commands for more details.

  2. If you have control over the script, it'd probably make more sense to split it up into two parts: a library-like file that just defines Julia functions (but doesn't run any analyses) and a command-line file that parses the arguments and calls the functions defined by the library. Both command-line interface and the second script your writing now can include the library — or better yet make the library-like file a full-fledged package.

Upvotes: 5

Dan Getz
Dan Getz

Reputation: 18227

This solution is not clean or Julia style of doing things. But if you insist:

To avoid the warning when messing with ARGS use the original ARGS but mutate its contents. Like the following:

empty!(ARGS)
push!(ARGS,"argument1")
push!(ARGS,"argument2")

include("file.jl")

And this question is also a duplicate, or related to: juliapassing-argument-to-the-includefile-jl as @AlexanderMorley pointed to.

Upvotes: 2

Related Questions