carlobaldassi / ArgParse.jl

Package for parsing command-line arguments to Julia programs.
Other
236 stars 36 forks source link

Parsing a numeric vector #115

Open fkrauer opened 2 years ago

fkrauer commented 2 years ago

Hi I have a script that takes some arguments, some of which are numeric vectors. Since the arguments passed to the command line need to be a string ("[0.1, 0.5]"), I am looking for ways to convert the string to a vector within the script. I found a solution if the string is a verbatim of julia syntax, but it does not work for something like [1.0:10.0:100.0;]. How can I parse such as vector? Here is a MWE (testparse.jl):

using ArgParse

s = ArgParseSettings()
@add_arg_table! s begin
    "--moo"
    arg_type = String
    "--foo"
    arg_type = String
end

args = parse_args(ARGS, s)

moo = Float64.(Meta.parse(args["moo"]).args)
println(moo)

foo = Float64.(Meta.parse(args["foo"]).args)
println(foo)

println(moo .* foo)

This works:

julia --project testparse.jl --foo="[1.0, 2.0, 3.0]" --moo="[1.0, 2.0, 3.0]"

But this doesn't work:

julia --project testparse.jl --foo="[1.0, 2.0, 3.0]" --moo="[1.0:10.0:100.0;]"
stepanzh commented 2 years ago

@fkrauer I'm not experienced with metaprogramming, but that seems like a solution

...
moo = float.(eval(Meta.parse(args["moo"])))

...
foo = float.(eval(Meta.parse(args["foo"])))
% j testparse.jl --foo="[1.0, 2.0, 3.0]" --moo="[4:4:12;]"
[4.0, 8.0, 12.0]
[1.0, 2.0, 3.0]
[4.0, 16.0, 36.0]