Argument table

Argument table

The argument table is used to store allowed arguments and options in an ArgParseSettings object.

Each entry of the table consist of an argument name and a list of argument settings, e.g.:

"--verbose"
    help = "verbose output"
    action = :store_true

There are two very similar methods to populate a table:

@add_arg_table(settings, table...)

This macro adds a table of arguments and options to the given settings. It can be invoked multiple times. The arguments groups are determined automatically, or the current default group is used if specified (see the Argument groups section for more details).

The table is a list in which each element can be either String, or a tuple or a vector of String, or an assigmment expression, or a block:

  • a String, a tuple or a vector introduces a new positional argument or option. Tuples and vectors are only allowed for options and provide alternative names (e.g. ["--opt", "-o"])
  • assignment expressions (i.e. expressions using =, := or =>) describe the previous argument behavior (e.g. help = "an option" or required => false). See the Argument entry settings section for a complete description
  • blocks (begin...end or lists of expressions in parentheses separated by semicolons) are useful to group entries and span multiple lines.

These rules allow for a variety usage styles, which are discussed in the Argument table styles section. In the rest of the documentation, we will mostly use this style:

@add_arg_table settings begin
    "--opt1", "-o"
        help = "an option with an argument"
    "--opt2"
    "arg1"
        help = "a positional argument"
        required = true
end

In the above example, the table is put in a single begin...end block and the line "--opt1", "-o" is parsed as a tuple; indentation is used to help readability.

See also the function add_arg_table.

source
add_arg_table(settings, [arg_name [,arg_options]]...)

This function is very similar to the macro version @add_arg_table. Its syntax is stricter: tuples and blocks are not allowed and argument options are explicitly specified as Dict objects. However, since it doesn't involve macros, it offers more flexibility in other respects, e.g. the arg_name entries need not be explicit, they can be anything which evaluates to a String or a Vector{String}.

Example:

add_arg_table(settings,
    ["--opt1", "-o"],
    Dict(
        :help => "an option with an argument"
    ),
    "--opt2",
    "arg1",
    Dict(
        :help => "a positional argument"
        :required => true
    ))
source

Argument names

Argument names are strings or, in the case of options, lists of strings. An argument is an option if it begins with a '-' character, otherwise it'a positional argument. A single '-' introduces a short option, which must consist of a single character; long options begin with "--" instead.

Positional argument names can be any string, except all-uppercase strings between '%' characters, which are reserved (e.g. "%COMMAND%"). Option names can contain any character except '=', whitespaces and non-breakable spaces. Depending on the value of the add_help and add_version settings, options --help, -h and --version may be reserved. If the allow_ambiguous_opts setting is false, some characters are not allowed as short options: all digits, the dot, the underscore and the opening parethesis (e.g. -1, -., -_, -().

For positional arguments, the argument name will be used as the key in the Dict object returned by the parse_args function. For options, it will be used to produce a default key in case a dest_name is not explicitly specified in the table entry, using either the first long option name in the list or the first short option name if no long options are present. For example:

argument namedefault dest_name
"--long""long"
"--long", "-s""long"
"-s", "--long1", "--long2""long1"
"-s", "-x""s"

In case the autofix_names setting is true (it is false by default), dashes in the names of arguments and long options will be converted to underscores: for example, "--my-opt" will yield "my_opt" as the default dest_name.

The argument name is also used to generate a default metavar in case metavar is not explicitly set in the table entry. The rules are the same used to determine the default dest_name, but for options the result will be uppercased (e.g. "--long" will become LONG). Note that this poses additional constraints on the positional argument names (e.g. whitespace is not allowed in metavars).

Argument entry settings

Argument entry settings determine all aspects of an argument's behavior. Some settings combinations are contradictory and will produce an error (e.g. using both action = :store_true and nargs = 1, or using action = :store_true with a positional argument). Also, some settings are only meaningful under some conditions (e.g. passing a metavar to a flag-like option does not make sense) and will be ignored with a warning (unless the suppress_warnings general setting is true).

This is the list of all available settings:

Available actions and nargs values

The nargs and action argument entry settings are used together to determine how many tokens will be parsed from the command line and what action will be performed on them.

The nargs setting can be a number or a character; the possible values are:

Actions can be categorized in many ways; one prominent distinction is flag vs. non-flag: some actions are for options which take no argument (i.e. flags), all others (except command, which is special) are for other options and positional arguments:

This is the list of all available actions (in each example, suppose we defined settings = ArgParseSettings()):

Commands

Commands are a special kind of arguments which introduce sub-parsing sessions as soon as they are encountered by parse_args (and are therefore mutually exclusive). The ArgParse module allows commands to look both as positional arguments or as flags, with minor differences between the two.

Commands are introduced by the action = :command setting in the argument table. Suppose we save the following script in a file called cmd_example.jl:

using ArgParse

function parse_commandline()
    s = ArgParseSettings()

    @add_arg_table s begin
        "cmd1"
            help = "first command"
            action = :command
        "cmd2"
            help = "second command"
            action = :command
    end

    return parse_args(s)
end

parsed_args = parse_commandline()
println(parsed_args)

Invoking the script from the command line, we would get the following help screen:

$ julia cmd_example.jl --help
usage: cmd_example.jl [-h] {cmd1|cmd2}

commands:
  cmd1        first command
  cmd2        second command

optional arguments:
  -h, --help  show this help message and exit

If commands are present in the argument table, parse_args will set the special key "%COMMAND%" in the returned Dict and fill it with the invoked command (or nothing if no command was given):

$ julia cmd_example.jl cmd1
Dict("%COMMAND%"=>"cmd1", "cmd1"=>Dict())

This is unless parse_args is invoked with as_symbols=true, in which case the special key becomes :_COMMAND_. (In that case, no other argument is allowed to use _COMMAND_ as its dest_name, or an error will be raised.)

Since commands introduce sub-parsing sessions, an additional key will be added for the called command ("cmd1" in this case) whose associated value is another Dict{String, Any} containing the result of the sub-parsing (in the above case it's empty). In fact, with the default settings, commands have their own help screens:

$ julia cmd_example.jl cmd1 --help
usage: cmd_example.jl cmd1 [-h]

optional arguments:
  -h, --help  show this help message and exit

The argument settings and tables for commands can be accessed by using a dict-like notation, i.e. settings["cmd1"] is an ArgParseSettings object specific to the "cmd1" command. Therefore, to populate a command sub-argument-table, simply use @add_arg_table(settings["cmd1"], table...) and similar.

These sub-settings are created when a command is added to the argument table, and by default they inherit their parent general settings except for the prog setting (which is auto-generated, as can be seen in the above example) and the description, epilog and usage settings (which are left empty).

Commands can also have sub-commands.

By default, if commands exist, they are required; this can be avoided by setting the commands_are_required = false general setting.

The only meaningful settings for commands in an argument entry besides action are help, force_override, group and (for flags only) dest_name.

The only differences between positional-arguments-like and flag-like commands are in the way they are parsed, the fact that flags accept a dest_name setting, and that flags can have multiple names (e.g. a long and short form).

Note that short-form flag-like commands will be still be recognized in the middle of a short options group and trigger a sub-parsing session: for example, if a flag -c is associated to a command, then -xch will parse option -x according to the parent settings, and option -h according to the command sub-settings.

Argument groups

By default, the auto-generated help screen divides arguments into three groups: commands, positional arguments and optional arguments, displayed in that order. Example:

julia> settings = ArgParseSettings(exit_after_help = false);

┌ Warning: Deprecated syntax `underscores as an rvalue`.
└ @ none:0

julia> @add_arg_table settings begin
          "--opt"
          "arg"
            required = true
          "cmd1"
            action = :command
          "cmd2"
            action = :command
       end;

┌ Warning: Deprecated syntax `underscores as an rvalue`.
└ @ none:0

julia> parse_args(["--help"], settings)
usage: make.jl [--opt OPT] [-h] arg {cmd1|cmd2}

commands:
  cmd1
  cmd2

positional arguments:
  arg

optional arguments:
  --opt OPT
  -h, --help  show this help message and exit

It is possible to partition the arguments differently by defining and using customized argument groups.

add_arg_group(settings, description, [name , [set_as_default]])

This function adds an argument group to the argument table in settings. The description is a String used in the help screen as a title for that group. The name is a unique name which can be provided to refer to that group at a later time.

After invoking this function, all subsequent invocations of the @add_arg_table macro and add_arg_table function will use the new group as the default, unless set_as_default is set to false (the default is true, and the option can only be set if providing a name). Therefore, the most obvious usage pattern is: for each group, add it and populate the argument table of that group. Example:

julia> settings = ArgParseSettings();

julia> add_arg_group(settings, "custom group");

julia> @add_arg_table settings begin
          "--opt"
          "arg"
       end;

julia> parse_args(["--help"], settings)
usage: <command> [--opt OPT] [-h] [arg]

optional arguments:
  -h, --help  show this help message and exit

custom group:
  --opt OPT
  arg

As seen from the example, new groups are always added at the end of existing ones.

The name can also be passed as a Symbol. Forbidden names are the standard groups names ("command", "positional" and "optional") and those beginning with a hash character '#'.

source
set_default_arg_group(settings, [name])

Set the default group for subsequent invocations of the @add_arg_table macro and add_arg_table function. name is a String, and must be one of the standard group names ("command", "positional" or "optional") or one of the user-defined names given in add_arg_group (groups with no assigned name cannot be used with this function).

If name is not provided or is the empty string "", then the default behavior is reset (i.e. arguments will be automatically assigned to the standard groups). The name can also be passed as a Symbol.

source

Besides setting a default group with add_arg_group and set_default_group, it's also possible to assign individual arguments to a group by using the group setting in the argument table entry, which follows the same rules as set_default_group.

Note that if the add_help or add_version general settings are true, the --help, -h and --version options will always be added to the optional group.

Argument table styles

Here are some examples of styles for the @add_arg_table marco and add_arg_table function invocation:

@add_arg_table settings begin
    "--opt", "-o"
        help = "an option"
    "arg"
        help = "a positional argument"
end

@add_arg_table(settings
    , ["--opt", "-o"]
    ,    help => "an option"
    , "arg"
    ,    help => "a positional argument"
    )

@add_arg_table settings begin
    (["--opt", "-o"]; help = an option)
    ("arg"; help = "a positional argument")
end

@add_arg_table(settings,
    ["-opt", "-o"],
    begin
        help = "an option"
    end,
    "arg",
    begin
        help = "a positional argument"
    end)

add_arg_table(settings,
    ["-opt", "-o"], Dict(:help => "an option"),
    "arg"         , Dict(:help => "a positional argument")
    )

One restriction is that groups introduced by begin...end blocks or semicolon-separated lists between parentheses cannot introduce argument names unless the first item in the block is an argument name.