1

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.

Community
  • 1
  • 1
a06e
  • 18,594
  • 33
  • 93
  • 169

1 Answers1

5

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.

Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67
  • If an argument has a default value, can I know if it was passed? – a06e Apr 04 '16 at 12:44
  • @becko You can compare it to the default value... but if the user introduces exactly the default value I couldn't find a way of differenciating the two cases. – Imanol Luengo Apr 04 '16 at 16:45