Skip to content

Instantly share code, notes, and snippets.

@carlobaldassi
Created September 4, 2012 08:52
Show Gist options
  • Save carlobaldassi/3618699 to your computer and use it in GitHub Desktop.
Save carlobaldassi/3618699 to your computer and use it in GitHub Desktop.
ArgParse examples
# example 1: minimal options/arguments, auto-generated help/version
require("argparse.jl")
import ArgParse.*
function main(args)
s = ArgParseSettings()
s.prog = "argparse_example_1.jl" # program name (for usage & help screen)
s.description = "Example 1 for argparse.jl: minimal usage." # desciption (for help screen)
@add_arg_table s begin
"--opt1" # an option (will take an argument)
"--opt2", "-o" # another option, with short form
"arg1" # a positional argument
end
parsed_args = parse_args(args, s) # the result is a Dict{String,Any}
println("Parsed args:")
for pa in parsed_args
println(" $(pa[1]) => $(pa[2])")
end
end
main(ARGS)

Auto-generated help screen:

$ julia ./argparse_example1.jl --help
usage: argparse_example_1.jl [--opt1 OPT1] [-o OPT2] [-h] [arg1]

Example 1 for argparse.jl: minimal usage.

positional arguments:
  arg1

optional arguments:
  --opt1 OPT1
  -o, --opt2 OPT2
  -h, --help       show this help message and exit

A syntax error will produce a message and show the usage line:

$ julia ./argparse_example1.jl --opt1
option --opt1 requires an argument
usage: argparse_example_1.jl [--opt1 OPT1] [-o OPT2] [-h] [arg1]

Example of a successful run:

$ julia ./argparse_example1.jl -o TST
Parsed args:
  arg1  =>  nothing
  opt2  =>  TST
  opt1  =>  nothing

note that if no default is specified, the value will be nothing.

# example 2: add some flags and the help lines for options
require("argparse.jl")
import ArgParse.*
function main(args)
s = ArgParseSettings("argparse_example_2.jl", # prog name
"Example 2 for argparse.jl: " * # description
"flags, options help, " *
"required arguments.")
@add_arg_table s begin
"--opt1"
help = "an option" # used by the help screen
"--opt2", "-o"
action = :store_true # this makes it a flag
help = "a flag"
"arg1"
help = "an argument"
required = true # makes the argument mandatory
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for pa in parsed_args
println(" $(pa[1]) => $(pa[2])")
end
end
main(ARGS)

Help screen:

$ julia ./argparse_example2.jl --help
usage: argparse_example_2.jl [--opt1 OPT1] [-o] [-h] arg1

Example 2 for argparse.jl: flags, options help, required arguments.

positional arguments:
  arg1         an argument

optional arguments:
  --opt1 OPT1  an option
  -o, --opt2   a flag
  -h, --help   show this help message and exit

The argument is now required:

$ julia ./argparse_example2.jl --opt2
required argument arg1 was not provided
usage: argparse_example_2.jl [--opt1 OPT1] [-o] [-h] arg1

opt2 is a Bool

$ julia ./argparse_example2.jl TST
Parsed args:
  arg1  =>  TST
  opt2  =>  false
  opt1  =>  nothing
$ julia ./argparse_example2.jl --opt2 TST
Parsed args:
  arg1  =>  TST
  opt2  =>  true
  opt1  =>  nothing
# example 3: version information, default values, options with
# types and variable number of arguments
require("argparse.jl")
import ArgParse.*
function main(args)
s = ArgParseSettings("Example 3 for argparse.jl", true,
"Version 1.0", true)
s = ArgParseSettings("argparse_example_3.jl",
"Example 3 for argparse.jl: " *
"version info, default values, " *
"options with types, variable " *
"number of arguments.")
s.version = "Version 1.0" # version info
s.add_version = true # audo-add version option
@add_arg_table s begin
"--opt1"
nargs = '?' # '?' means optional argument
arg_type = Int # only Int arguments allowed
default = 0 # this is used when the option is not passed
constant = 1 # this is used if --opt1 is paseed with no argument
help = "an option"
"--karma", "-k"
action = :count_invocations # increase a counter each time the option is given
help = "increase karma"
"arg1"
nargs = 2 # eats up two arguments; puts the result in a Vector
help = "first argument, two " *
"entries at once"
required = true
"arg2"
nargs = '*' # eats up as many arguments as possible before an option
default = {"no_arg_given"} # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
help = "second argument, eats up " *
"as many items as possible " *
"before an option"
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for pa in parsed_args
println(" $(pa[1]) => $(pa[2])")
end
end
main(ARGS)

Help screen (notice it prints defaults and types):

$ julia ./argparse_example3.jl --help
usage: argparse_example_3.jl [--opt1 [OPT1]] [-k] [--version] [-h]
                             arg1 arg1 [arg2...]

Example 3 for argparse.jl: version info, default values, options with
types, variable number of arguments.

positional arguments:
  arg1           first argument, two entries at once
  arg2           second argument, eats up as many items as possible
                 before an option (default: {"no_arg_given"})

optional arguments:
  --opt1 [OPT1]  an option (type: Int64, default: 0, without arg: 1)
  -k, --karma    increase karma
  --version      show version information and exit
  -h, --help     show this help message and exit

Version information:

$ julia ./argparse_example3.jl --version
Version 1.0

Examples of successful runs:

$ julia argparse_example3.jl -k -k A1 A1 A2 A2 A2 -k --opt1 5
Parsed args:
  karma  =>  3
  arg1  =>  {"A1", "A1"}
  arg2  =>  {"A2", "A2", "A2"}
  opt1  =>  5
$ julia argparse_example3.jl -k -k A1 A1 A2 A2 A2 -k --opt1
Parsed args:
  karma  =>  3
  arg1  =>  {"A1", "A1"}
  arg2  =>  {"A2", "A2", "A2"}
  opt1  =>  1

The type of the argument is checked immediately:

$ julia argparse_example3.jl --opt1 NONINT
invalid argument: NONINT (must be of type Int64)
usage: argparse_example_3.jl [--opt1 [OPT1]] [-k] [--version] [-h]
                             arg1 arg1 [arg2...]
# example 4: dest_name, metavar, range_tester, alternative
# actions
require("argparse.jl")
import ArgParse.*
function main(args)
s = ArgParseSettings("argparse_example_4.jl",
"Example 4 for argparse.jl: " *
"more tweaking of the arg fields: " *
"dest_name, metvar, range_tested, " *
"alternative actions.")
@add_arg_table s begin
"--opt1"
action = :append_const # appends 'constant' to 'dest_name'
arg_type = String
constant = "O1"
dest_name = "O_stack" # this changes the destination
help = "append O1"
"--opt2"
action = "append_const"
arg_type = String
constant = "O2"
dest_name = "O_stack" # same dest_name as opt1, different constant
help = "append O2"
"-k"
action = "store_const" # stores constant if given, default otherwise
default = 0
constant = 42
help = "provide the answer"
"--awkward-option"
nargs = '+' # eats up as many argument as found (at least 1)
action = "append_arg" # argument chunks are appended when the option is
# called repeatedly
dest_name = "awk"
range_tester = (x->x=="X"||x=="Y") # each argument must be either "X" or "Y"
metavar = "XY"
help = "either X or Y; all XY's are " *
"stored in chunks"
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for pa in parsed_args
println(" $(pa[1]) => $(pa[2])")
end
end
main(ARGS)

Help screen

$ julia argparse_example4.jl  --help
usage: argparse_example_4.jl [--opt1] [--opt2] [-k]
                             [--awkward-option XY [XY...]] [-h]

Example 4 for argparse.jl: more tweaking of the arg fields: dest_name,
metvar, range_tested, alternative actions.

optional arguments:
  --opt1                append O1
  --opt2                append O2
  -k                    provide the answer
  --awkward-option XY [XY...]
                        either X or Y; all XY's are stored in chunks
  -h, --help            show this help message and exit

Run with default values:

$ julia argparse_example4.jl
Parsed args:
  k  =>  0
  awk  =>  []
  O_stack  =>  []

Long options can be abbreviated as long as there is no ambiguity. Also, see the range_tester in action:

$ julia argparse_example4.jl  --awk Z
out of range argument to option --awkward-option: Z
usage: argparse_example_4.jl [--opt1] [--opt2] [-k]
                             [--awkward-option XY [XY...]] [-h]

When --awkward-option is paseed, it eats up many arguments at once and puts them in a Vector (because of nargs='+'. When passed multiple times, those vectors are appended, because of action=append_arg. When --opt1 and --opt2 are passed, they append their constant to the same vector, since they have the same dest_name.

$ julia argparse_example4.jl --awkw X Y X --opt1 --opt1 --awkward X X --opt2 --awk Y -k
Parsed args:
  k  =>  42
  awk  =>  [{"X", "Y", "X"}, {"X", "X"}, {"Y"}]
  O_stack  =>  ["O1", "O1", "O2"]
# example 5: manual help/version, import another parser
require("argparse.jl")
import ArgParse.*
function main(args)
s0 = ArgParseSettings() # a "parent" structure e.g. one with some useful set of rules
# which we want to extend
# So we just add a simple table
@add_arg_table s0 begin
"--parent-flag", "-o"
action=>"store_true"
help=>"parent flag"
"--flag"
action=>"store_true"
help=>"another parent flag"
"parent-argument"
help = "parent argument"
end
s = ArgParseSettings("argparse_example_5.jl",
"Example 5 for argparse.jl: " *
"importing another parser, " *
"manual help and version.")
s.add_help = false # disable auto-add of --help option
s.version = "Version 1.0" # we set the version info, but --version won't be added
import_settings(s, s0) # now s has all of s0 arguments (except help/version)
s.error_on_conflict = false # do not error-out when trying to override an option
@add_arg_table s begin
"-o" # this will partially override s0's --parent-flag
action = :store_true
help = "child flag"
"--flag" # this will fully override s0's --flag
action = :store_true
help = "another child flag"
"-?", "--HELP", "--¡ḧëļṕ" # (almost) all characters allowed
action = :show_help # will invoke the help generator
help = "this will help you"
"-v", "--VERSION"
action = :show_version # will show version information
help = "show version information" *
"and exit"
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for pa in parsed_args
println(" $(pa[1]) => $(pa[2])")
end
end
main(ARGS)

Help screen. Notice that the "parent" options and arguments are mixed with the ones of the "child", having been partially overridden by them.

$ julia argparse_example5.jl -?
usage: argparse_example_5.jl [--parent-flag] [-o] [--flag] [-?] [-v]
                             [parent-argument]

Example 5 for argparse.jl: importing another parser, manual help and
version.

positional arguments:
  parent-argument      parent argument

optional arguments:
  --parent-flag        parent flag
  -o                   child flag
  --flag               another child flag
  -?, --HELP, --¡ḧëļṕ  this will help you
  -v, --VERSION        show version informationand exit

Show version:

$ julia argparse_example5.jl -v
Version 1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment