Pass command line arguments to a sub-script loaded by a script

Hi,
I have scripts, which do some calculation and I have scripts which setup workers, on a local machine, on remote machines, with a machinefile, etc. I want to pass arguments from the command line, which are in Base.ARGS, to the second script, namely all arguments except e.g. the first - something like

# driver_script.jl

arg1 = ARGS[1]

println(arg1)

ARGS = [ARGS[2:end]...]
includ("calculation_script.jl")

does not work as we can not reset Base.ARGS. How do I pass arguments to “calculation_script.jl”?

How about

run("julia calculation_script.jl $(join(ARGS, ' '))")

?

Though honestly, for anything complicated enough to require 2 files, I’d have all the actual calculations in a single script, and have the includes be just functions, types, and constants.

You can. You can for example use popfirst!:

arg1 = popfirst!(ARGS) # ARGS now contains just the rest

or you can use empty!:

arg1 = ARGS[1]
tmp = ARGS[2:end]
empty!(ARGS)
append!(ARGS, tmp)

etc.

3 Likes

@fredrikekre Thanks for your answer! This is exactly what I was looking for! :slight_smile:

also you have the option to load the setup of workers script with the -L flag
like

julia -L workers.jl script.jl args

@BeastyBlacksmith Thanks for pointing this out as well! Can I pass arguments to workers.jl and script.jl seperately? E.g. number of workers to workers.jl and parameters to script.jl?

From a quick test it seems to me that the arguments you pass are available to both files

julia -L test.jl test.jl a b
["a","b"]
["a","b"]

with test.jl:

println(ARGS)

So no seperate argument passing, but you can pick out, what you need.

OK. Can I pass arguments as key-value-pairs as well, like --worker_count 4 and --param1 0.43 ? As far as I can see, I can only retrieve the arguments as positions in ARGS, e.g. ARGS[1], etc ?

You might be interested in https://github.com/carlobaldassi/ArgParse.jl

2 Likes

Looks promising! I will have a look into it!