This is essentially the same question as: Check if argparse optional argument is set or not, but in Julia, using Julia's ArgParse module.
Given an argument that takes a value, I want to know if its value was given or not.
This is essentially the same question as: Check if argparse optional argument is set or not, but in Julia, using Julia's ArgParse module.
Given an argument that takes a value, I want to know if its value was given or not.
In short, once you have parsed the arguments, you can check if an argument was set as parsed_args["argname"] == nothing
(will return true
if it was not set).
Find bellow a self-contained example (sightly modified example1 from ArgParse.jl
) with 2 arguments that prints true if an argument was not set (just replace ==
with !=
for the opposite behaviour):
using ArgParse
function main(args)
# initialize the settings (the description is for the help screen)
s = ArgParseSettings(description = "Example usage")
@add_arg_table s begin
"--opt1" # an option (will take an argument)
"arg1" # a positional argument
end
parsed_args = parse_args(s) # the result is a Dict{String,Any}
println(parsed_args["arg1"] == nothing)
println(parsed_args["opt1"] == nothing)
end
main(ARGS)
And example command line calls (assuming above is stored in test.jl
):
>>> julia test.jl
true
true
>>> julia test.jl 5
false
true
>>> julia test.jl 5 --opt1=6
false
false
>>> julia test.jl --opt1=6
true
false
However, sometimes it might be more appropriate to define a default value for the parameter rather than checking if it was set. It can be done by adding the default
keyword to the parameter:
@add_arg_table s begin
"--opt1"
"--opt2", "-o"
arg_type = Int
default = 0
"arg1"
required = true
end
aswell as the required
keyword for the positional parameters, which would force the user to introduce it.