Skip to content

Instantly share code, notes, and snippets.

@carlobaldassi
Created September 13, 2012 23:30
Show Gist options
  • Save carlobaldassi/3718579 to your computer and use it in GitHub Desktop.
Save carlobaldassi/3718579 to your computer and use it in GitHub Desktop.
ArgParse examples #2
# example 6: commands & subtables
require("argparse.jl")
import ArgParse.*
function main(args)
s = ArgParseSettings("argparse_example_6.jl",
"Example 6 for argparse.jl: " *
"commands and their associated subtables.")
@add_arg_table s begin
"run"
action = :command # adds a command which will be read from an argument
help = "start running mode"
"jump"
action = :command
help = "start jumping mode"
end
@add_arg_table s["run"] begin # add command arg_table: same as usual, but invoked on s["cmd"]
"--speed"
arg_type = Float64
default = 10.
help = "running speed, in Å/month"
end
@add_arg_table s["jump"] begin
"--higher"
action = :store_true
help = "enhance jumping"
"--somersault"
action = :command # this adds a sub-command (read from an option instead)
dest_name = "som" # flag commands can set a dest_name
help = "somersault jumping mode"
"--clap-feet"
action = :command
help = "clap feet jumping mode"
end
s["jump"].description = "Jump mode for example 6" # this is how settings are tweaked
# for commands
s["jump"].commands_are_required = false # this makes the sub-commands optional
s["jump"]["som"].description = "Somersault jump " * # this is how settings are tweaked
"mode for example 6" # for sub-commands
parsed_args = parse_args(args, s)
println("Parsed args:")
for pa in parsed_args
println(" $(pa[1]) => $(pa[2])")
end
println()
# parsed_args will have a special field "%COMMAND%"
# which will hold the executed command name (or 'nothing')
println("Command: ", parsed_args["%COMMAND%"])
# thus, the command args are in parsed_args[parsed_args["%COMMAND%]]
println("Parsed command args:")
command_args = parsed_args[parsed_args["%COMMAND%"]]
for pa in command_args
println(" $(pa[1]) => $(pa[2])")
end
end
main(ARGS)

Help screen:

$ julia argparse_example6.jl --help
usage: argparse_example_6.jl [-h] {run|jump}

Example 6 for argparse.jl: commands and their associated subtables.

commands:
  run         start running mode
  jump        start jumping mode

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

Passing a wrong command:

$ julia argparse_example6.jl fly
unknown command: fly
usage: argparse_example_6.jl [-h] {run|jump}

Commands have their own sub-helps:

$ julia argparse_example6.jl run --help
usage: argparse_example_6.jl run [--speed SPEED] [-h]

optional arguments:
  --speed SPEED  running speed, in Å/month (type: Float64, default:
                 10.0)
  -h, --help     show this help message and exit

$ julia argparse_example6.jl jump --help
usage: argparse_example_6.jl jump [--higher] [-h]
                        [--somersault|--clap-feet]

Jump mode for example 6

commands:
  --somersault  somersault jumping mode
  --clap-feet   clap feet jumping mode

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

$ julia argparse_example6.jl jump --clap-feet --help
usage: argparse_example_6.jl jump --clap-feet [-h]

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

The --clap-feet sub-command has only the auto-added help, since we didn't provide and arg table.

Here is how the resulting Dict looks like:

$ julia argparse_example6.jl run --speed "3*10^8"
Parsed args:
  run  =>  {"speed"=>3.0e8}
  %COMMAND%  =>  run

Command: run
Parsed command args:
  speed  =>  3.0e8

Aside note: we passed an integer expression as option, it was evaluated and converted to Float64.

Another run:

$ julia argparse_example6.jl jump --higher
Parsed args:
  %COMMAND%  =>  jump
  jump  =>  {"%COMMAND%"=>nothing,"higher"=>true}

Command: jump
Parsed command args:
  %COMMAND%  =>  nothing
  higher  =>  true

Need to go deeper?

$ julia argparse_example6.jl jump --clap-feet
Parsed args:
  %COMMAND%  =>  jump
  jump  =>  {"clap-feet"=>Dict{String,Any}(),"%COMMAND%"=>"clap-feet","higher"=>false}

Command: jump
Parsed command args:
  clap-feet  =>  Dict{String,Any}()
  %COMMAND%  =>  clap-feet
  higher  =>  false
# example 7: argument groups
require("argparse.jl")
import ArgParse.*
function main(args)
s = ArgParseSettings("argparse_example_7.jl",
"Example 7 for argparse.jl: " *
"argument groups.")
add_arg_group(s, "stack options") # add a group and sets it as the default
@add_arg_table s begin # all options (and arguments) in this table
# will be assigned to the newly added group
"--opt1"
action = :append_const
arg_type = String
constant = "O1"
dest_name = "O_stack"
help = "append O1 to the stack"
"--opt2"
action = :append_const
arg_type = String
constant = "O2"
dest_name = "O_stack"
help = "append O2 to the stack"
end
add_arg_group(s, "weird options", "weird") # another group, this time with a tag which allows
# to refer to it
set_default_arg_group(s, "weird") # set the default group (useless here, since we just added it)
@add_arg_table s begin
"--awkward-option"
nargs = '+'
action = :append_arg
dest_name = "awk"
range_tester = (x->x=="X"||x=="Y")
metavar = "XY"
help = "either X or Y; all XY's are " *
"stored in chunks"
end
set_default_arg_group(s) # reset the default arg group (which means arguments
# are automatically assigned to commands/options/pos.args
# groups)
@add_arg_table s begin
"-k"
action = :store_const
default = 0
constant = 42
help = "provide the answer"
"--şİłłÿ"
action = :store_true
help = "an option with a silly name"
group = "weird" # this overrides the default group: this option
# will be grouped together with --awkward-option
end
println("groups = ", get_arg_groups(s))
parsed_args = parse_args(args, s)
println("Parsed args:")
for pa in parsed_args
println(" $(pa[1]) => $(pa[2])")
end
end
main(ARGS)

This example is almost identical to example 4, but the help screen is rearranged in groups:

$ julia argparse_example7.jl --help
usage: argparse_example_7.jl [--opt1] [--opt2]
                        [--awkward-option XY [XY...]] [-k] [--şİłłÿ]
                        [-h]

Example 7 for argparse.jl: argument groups.

optional arguments:
  -k                    provide the answer
  -h, --help            show this help message and exit

stack options:
  --opt1                append O1 to the stack
  --opt2                append O2 to the stack

weird options:
  --awkward-option XY [XY...]
                        either X or Y; all XY's are stored in chunks
  --şİłłÿ               an option with a silly name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment