Reputation: 592
Is there a way to pass a vector variable as a command line argument in Julia? In my case I have two arguments: an integer and a vector of integers. While I can easily parse the first argument, I didn't find any pleasant way to parse a vector. For now I simply set the vector to be v = parse.(Int, ARGS[2:end])
but it is quite confusing since the items of the vector are treated as arguments. Is there a some special syntax to treat such cases?
Upvotes: 2
Views: 1505
Reputation: 20298
I think your current solution is fine as it is, and in line with the way many command-line tools do things.
If you really want to pass your whole array as one command-line argument, you'll have to:
Both steps vary depending on the syntax you want to use.
Two examples:
example 1: Julia-like syntax
shell$ julia myscript.jl 42 "[1,2,3]"
i = 42
v = [1, 2, 3]
We can take advantage of the Julia parser being able to parse such arrays (but let's be cautious about not evaluating arbitrary julia code input by the user):
# First argument: an integer
i = parse(Int, ARGS[1])
# Second argument, a Vector{Int} in Julia-like format: "[1, 2, 3]"
v = let expr = Meta.parse(ARGS[2])
@assert expr.head == :vect
Int.(expr.args)
end
@show i
@show v
Example 2: space- or comma-separated values
shell$ julia myscript.jl 42 "1,2,3"
i = 42
v = [1, 2, 3]
Here, we can use DelimitedFiles
to parse the array (change the delimiter to whatever you like):
# First argument: an integer
i = parse(Int, ARGS[1])
# Second argument, a Vector{Int} as comma-separated values
using DelimitedFiles
v = reshape(readdlm(IOBuffer(ARGS[2]), ',', Int), :)
# set the delimiter here ^
@show i
@show v
Upvotes: 5