# Python : Core Library : Argparse ## Cheatsheet ```python from argparse import Action, ArgumentParser, HelpFormatter, Namespace ``` ```python parser = ArgumentParser() parser.add_argument( "filename" ) # positional argument (to make optional, add nargs="?") parser.add_argument( "-c", "--count" ) # option that takes a value parser.add_argument( "-v", "--verbose", action="store_true" ) # on/off flag args = self.parser.parse_args([ ...tokens... ]) # defaults to parsing sys.argv[ 1: ] args.filename, args.count, args.verbose # access args as attributes; returns None if no arg or default ``` ## Reference #### ArgumentParser ```python ArgumentParser( # all params should be passed as kwargs prog = None # default: os.path.basename( sys.argv[ 0 ] ) usage = None # default: generated from parser args description = None # default: nothing (displayed before arg help) epilog = None # default: nothing (displayed after arg help) parents = [] # parent parsers — args will be included formatter_class = HelpFormatter # for help output prefix_chars = '-' # set of chars that prefix optional args fromfile_prefix_chars = None argument_default = None conflict_handler = 'error' add_help = True # add -h/--help option; set to False for parent parsers to avoid duplication allow_abbrev = True # support all unambiguous abbreviations of long options exit_on_error = True ) ``` #### Argument Definitions ```python add_argument( name or flags... # name ("foo") or list of option strings ("-f","--foo") [, action] [, nargs] # number of args to consume; "?" -> scalar, "*" / "+" / <int> -> list [, const] # a value required by some action and nargs selections [, default] [, type] # type to convert to [, choices] # sequence of allowable values [, required] [, help] # description [, metavar] # name used in help message [, dest] # name of attr in results obj [, deprecated] ) ``` ###### Actions Only actions that consume command-line arguments (`store`, `append` or `extend`) can be used with positional arguments. ```python store default store_const store the value in "const" param store_true store_false append store values from all occurances of option as list append_const store value from "const" for each occurance of option as list extend like append but can accept and store multiple values with a single occurance count store count of occurances of option (ex: -vvv -> 3) help print help and exit version ``` Can [define custom actions](https://docs.python.org/3/library/argparse.html#action). ###### Argument Groups ```python group = parser.add_mutually_exclusive_group( [required=True] ) group.add_argument( "-v", "--verbose", action="store_true" ) group.add_argument( "-q", "--quiet", action="store_true" ) # to provide default: group.add_argument( "-f", "--foo", action="store_const", dest="myvar", const="foo", default="foo" ) group.add_argument( "-b", "--bar", action="store_const", dest="myvar", const="bar") -or- group.add_argument( "-f", "--foo", action="store_const", dest="myvar", const="foo" ) group.add_argument( "-b", "--bar", action="store_const", dest="myvar", const="bar") parser.set_defaults( myvar="foo" ) ``` ## Examples ###### Positional ```python "foo" $ cmd # error: the following arguments are required: foo $ cmd abc # 'foo': 'abc' $ cmd abc def # error: unrecognized arguments: def "foo", nargs="?" $ cmd # 'foo': None $ cmd abc # 'foo': 'abc' $ cmd abc def # error: unrecognized arguments: def "foo", nargs="*" $ cmd # 'foo': [] $ cmd abc # 'foo': [ 'abc' ] $ cmd abc def # 'foo': [ 'abc', 'def' ] "foo", nargs="+" $ cmd # error: the following arguments are required: foo $ cmd abc # 'foo': [ 'abc' ] $ cmd abc def # 'foo': [ 'abc', 'def' ] "foo", nargs=1 $ cmd # error: the following arguments are required: foo $ cmd abc # 'foo': [ 'abc' ] $ cmd abc def # error: unrecognized arguments: def ``` ###### Positional + action="append" ```python "foo", action="append" $ cmd # error: the following arguments are required: foo $ cmd abc # 'foo': [ 'abc' ] $ cmd abc def # error: unrecognized arguments: def "foo", action="append", nargs="?" $ cmd # 'foo': [ None ] $ cmd abc # 'foo': [ 'abc' ] $ cmd abc def # error: unrecognized arguments: def "foo", action="append", nargs="*" $ cmd # 'foo': [[]] $ cmd abc # 'foo': [[ 'abc' ]] $ cmd abc def # 'foo': [[ 'abc', 'def' ]] "foo", action="append", nargs="+" $ cmd # error: the following arguments are required: foo $ cmd abc # 'foo': [[ 'abc' ]] $ cmd abc def # 'foo': [[ 'abc', 'def' ]] "foo", action="append", nargs=1 $ cmd # error: the following arguments are required: foo $ cmd abc # 'foo': [[ 'abc' ]] $ cmd abc def # error: unrecognized arguments: def ``` ###### Optional ```python "foo" $ cmd # 'foo': None $ cmd -f # error: argument -f/--foo: expected one argument $ cmd -f abc # 'foo': 'abc' $ cmd -f abc def # error: unrecognized arguments: def "foo", nargs="?" $ cmd # 'foo': None $ cmd -f # 'foo': None $ cmd -f abc # 'foo': 'abc' $ cmd -f abc def # error: unrecognized arguments: def "foo", nargs="*" $ cmd # 'foo': None $ cmd -f # 'foo': [] $ cmd -f abc # 'foo': [ 'abc' ] $ cmd -f abc def # 'foo': [ 'abc', 'def' ] "foo", nargs="+" $ cmd # 'foo': None $ cmd -f # error: argument -f/--foo: expected at least one argument $ cmd -f abc # 'foo': [ 'abc' ] $ cmd -f abc def # 'foo': [ 'abc', 'def' ] "foo", nargs=1 $ cmd # 'foo': None $ cmd -f # error: argument -f/--foo: expected 1 argument $ cmd -f abc # 'foo': [ 'abc' ] $ cmd -f abc def # error: unrecognized arguments: def ``` ###### Optional + action="append" ```python "foo", action="append" $ cmd # 'foo': None $ cmd -f # error: argument -f/--foo: expected one argument $ cmd -f abc # 'foo': 'abc' $ cmd -f abc def # error: unrecognized arguments: def "foo", action="append", nargs="?" $ cmd # 'foo': None $ cmd -f # 'foo': [ None ] $ cmd -f abc # 'foo': [ 'abc' ] $ cmd -f abc def # error: unrecognized arguments: def "foo", action="append", nargs="*" $ cmd # 'foo': None $ cmd -f # 'foo': [[]] $ cmd -f abc # 'foo': [['abc']] $ cmd -f abc def # 'foo': [['abc', 'def']] "foo", action="append", nargs="+" $ cmd # 'foo': None $ cmd -f # error: argument -f/--foo: expected at least one argument $ cmd -f abc # 'foo': [['abc']] $ cmd -f abc def # 'foo': [['abc', 'def']] "foo", action="append", nargs=1 $ cmd # 'foo': None $ cmd -f # error: argument -f/--foo: expected 1 argument $ cmd -f abc # 'foo': [['abc']] $ cmd -f abc def # error: unrecognized arguments: def ```