argparse — Parser for command-line options, arguments and sub-commands¶
New in version 3.2.
Source code:Lib/argparse.py
Tutorial
This page contains the API reference information. For a more gentleintroduction to Python command-line parsing, have a look at theargparse tutorial.
Theargparse module makes it easy to write user-friendly command-lineinterfaces. The program defines what arguments it requires, andargparsewill figure out how to parse those out ofsys.argv. Theargparsemodule also automatically generates help and usage messages and issues errorswhen users give the program invalid arguments.
Example¶
The following code is a Python program that takes a list of integers andproduces either the sum or the max:
importargparseparser=argparse.ArgumentParser(description='Process some integers.')parser.add_argument('integers',metavar='N',type=int,nargs='+',help='an integer for the accumulator')parser.add_argument('--sum',dest='accumulate',action='store_const',const=sum,default=max,help='sum the integers (default: find the max)')args=parser.parse_args()print(args.accumulate(args.integers))
Assuming the Python code above is saved into a file calledprog.py, it canbe run at the command line and provides useful help messages:
$pythonprog.py-husage: prog.py [-h] [--sum] N [N ...]Process some integers.positional arguments: N an integer for the accumulatoroptional arguments: -h, --help show this help message and exit --sum sum the integers (default: find the max)
When run with the appropriate arguments, it prints either the sum or the max ofthe command-line integers:
$pythonprog.py12344$pythonprog.py1234--sum10
If invalid arguments are passed in, it will issue an error:
$pythonprog.pyabcusage: prog.py [-h] [--sum] N [N ...]prog.py: error: argument N: invalid int value: 'a'
The following sections walk you through this example.
Creating a parser¶
The first step in using theargparse is creating anArgumentParser object:
>>>parser=argparse.ArgumentParser(description='Process some integers.')
TheArgumentParser object will hold all the information necessary toparse the command line into Python data types.
Adding arguments¶
Filling anArgumentParser with information about program arguments isdone by making calls to theadd_argument() method.Generally, these calls tell theArgumentParser how to take the stringson the command line and turn them into objects. This information is stored andused whenparse_args() is called. For example:
>>>parser.add_argument('integers',metavar='N',type=int,nargs='+',...help='an integer for the accumulator')>>>parser.add_argument('--sum',dest='accumulate',action='store_const',...const=sum,default=max,...help='sum the integers (default: find the max)')
Later, callingparse_args() will return an object withtwo attributes,integers andaccumulate. Theintegers attributewill be a list of one or more ints, and theaccumulate attribute will beeither thesum() function, if--sum was specified at the command line,or themax() function if it was not.
Parsing arguments¶
ArgumentParser parses arguments through theparse_args() method. This will inspect the command line,convert each argument to the appropriate type and then invoke the appropriate action.In most cases, this means a simpleNamespace object will be built up fromattributes parsed out of the command line:
>>>parser.parse_args(['--sum','7','-1','42'])Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
In a script,parse_args() will typically be called with noarguments, and theArgumentParser will automatically determine thecommand-line arguments fromsys.argv.
ArgumentParser objects¶
- class
argparse.ArgumentParser(prog=None,usage=None,description=None,epilog=None,parents=[],formatter_class=argparse.HelpFormatter,prefix_chars='-',fromfile_prefix_chars=None,argument_default=None,conflict_handler='error',add_help=True,allow_abbrev=True,exit_on_error=True)¶ Create a new
ArgumentParserobject. All parameters should be passedas keyword arguments. Each parameter has its own more detailed descriptionbelow, but in short they are:prog - The name of the program (default:
sys.argv[0])usage - The string describing the program usage (default: generated fromarguments added to parser)
description - Text to display before the argument help (default: none)
epilog - Text to display after the argument help (default: none)
parents - A list of
ArgumentParserobjects whose arguments shouldalso be includedformatter_class - A class for customizing the help output
prefix_chars - The set of characters that prefix optional arguments(default: ‘-‘)
fromfile_prefix_chars - The set of characters that prefix files fromwhich additional arguments should be read (default:
None)argument_default - The global default value for arguments(default:
None)conflict_handler - The strategy for resolving conflicting optionals(usually unnecessary)
add_help - Add a
-h/--helpoption to the parser (default:True)allow_abbrev - Allows long options to be abbreviated if theabbreviation is unambiguous. (default:
True)exit_on_error - Determines whether or not ArgumentParser exits witherror info when an error occurs. (default:
True)
Changed in version 3.5:allow_abbrev parameter was added.
Changed in version 3.8:In previous versions,allow_abbrev also disabled grouping of shortflags such as
-vvto mean-v-v.Changed in version 3.9:exit_on_error parameter was added.
The following sections describe how each of these are used.
prog¶
By default,ArgumentParser objects usesys.argv[0] to determinehow to display the name of the program in help messages. This default is almostalways desirable because it will make the help messages match how the program wasinvoked on the command line. For example, consider a file namedmyprogram.py with the following code:
importargparseparser=argparse.ArgumentParser()parser.add_argument('--foo',help='foo help')args=parser.parse_args()
The help for this program will displaymyprogram.py as the program name(regardless of where the program was invoked from):
$pythonmyprogram.py--helpusage: myprogram.py [-h] [--foo FOO]optional arguments: -h, --help show this help message and exit --foo FOO foo help$cd..$pythonsubdir/myprogram.py--helpusage: myprogram.py [-h] [--foo FOO]optional arguments: -h, --help show this help message and exit --foo FOO foo help
To change this default behavior, another value can be supplied using theprog= argument toArgumentParser:
>>>parser=argparse.ArgumentParser(prog='myprogram')>>>parser.print_help()usage: myprogram [-h]optional arguments: -h, --help show this help message and exit
Note that the program name, whether determined fromsys.argv[0] or from theprog= argument, is available to help messages using the%(prog)s formatspecifier.
>>>parser=argparse.ArgumentParser(prog='myprogram')>>>parser.add_argument('--foo',help='foo of the%(prog)s program')>>>parser.print_help()usage: myprogram [-h] [--foo FOO]optional arguments: -h, --help show this help message and exit --foo FOO foo of the myprogram program
usage¶
By default,ArgumentParser calculates the usage message from thearguments it contains:
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('--foo',nargs='?',help='foo help')>>>parser.add_argument('bar',nargs='+',help='bar help')>>>parser.print_help()usage: PROG [-h] [--foo [FOO]] bar [bar ...]positional arguments: bar bar helpoptional arguments: -h, --help show this help message and exit --foo [FOO] foo help
The default message can be overridden with theusage= keyword argument:
>>>parser=argparse.ArgumentParser(prog='PROG',usage='%(prog)s [options]')>>>parser.add_argument('--foo',nargs='?',help='foo help')>>>parser.add_argument('bar',nargs='+',help='bar help')>>>parser.print_help()usage: PROG [options]positional arguments: bar bar helpoptional arguments: -h, --help show this help message and exit --foo [FOO] foo help
The%(prog)s format specifier is available to fill in the program name inyour usage messages.
description¶
Most calls to theArgumentParser constructor will use thedescription= keyword argument. This argument gives a brief description ofwhat the program does and how it works. In help messages, the description isdisplayed between the command-line usage string and the help messages for thevarious arguments:
>>>parser=argparse.ArgumentParser(description='A foo that bars')>>>parser.print_help()usage: argparse.py [-h]A foo that barsoptional arguments: -h, --help show this help message and exit
By default, the description will be line-wrapped so that it fits within thegiven space. To change this behavior, see theformatter_class argument.
epilog¶
Some programs like to display additional description of the program after thedescription of the arguments. Such text can be specified using theepilog=argument toArgumentParser:
>>>parser=argparse.ArgumentParser(...description='A foo that bars',...epilog="And that's how you'd foo a bar")>>>parser.print_help()usage: argparse.py [-h]A foo that barsoptional arguments: -h, --help show this help message and exitAnd that's how you'd foo a bar
As with thedescription argument, theepilog= text is by defaultline-wrapped, but this behavior can be adjusted with theformatter_classargument toArgumentParser.
parents¶
Sometimes, several parsers share a common set of arguments. Rather thanrepeating the definitions of these arguments, a single parser with all theshared arguments and passed toparents= argument toArgumentParsercan be used. Theparents= argument takes a list ofArgumentParserobjects, collects all the positional and optional actions from them, and addsthese actions to theArgumentParser object being constructed:
>>>parent_parser=argparse.ArgumentParser(add_help=False)>>>parent_parser.add_argument('--parent',type=int)>>>foo_parser=argparse.ArgumentParser(parents=[parent_parser])>>>foo_parser.add_argument('foo')>>>foo_parser.parse_args(['--parent','2','XXX'])Namespace(foo='XXX', parent=2)>>>bar_parser=argparse.ArgumentParser(parents=[parent_parser])>>>bar_parser.add_argument('--bar')>>>bar_parser.parse_args(['--bar','YYY'])Namespace(bar='YYY', parent=None)
Note that most parent parsers will specifyadd_help=False. Otherwise, theArgumentParser will see two-h/--help options (one in the parentand one in the child) and raise an error.
Note
You must fully initialize the parsers before passing them viaparents=.If you change the parent parsers after the child parser, those changes willnot be reflected in the child.
formatter_class¶
ArgumentParser objects allow the help formatting to be customized byspecifying an alternate formatting class. Currently, there are four suchclasses:
- class
argparse.RawDescriptionHelpFormatter¶ - class
argparse.RawTextHelpFormatter¶ - class
argparse.ArgumentDefaultsHelpFormatter¶ - class
argparse.MetavarTypeHelpFormatter¶
RawDescriptionHelpFormatter andRawTextHelpFormatter givemore control over how textual descriptions are displayed.By default,ArgumentParser objects line-wrap thedescription andepilog texts in command-line help messages:
>>>parser=argparse.ArgumentParser(...prog='PROG',...description='''this description... was indented weird... but that is okay''',...epilog='''... likewise for this epilog whose whitespace will... be cleaned up and whose words will be wrapped... across a couple lines''')>>>parser.print_help()usage: PROG [-h]this description was indented weird but that is okayoptional arguments: -h, --help show this help message and exitlikewise for this epilog whose whitespace will be cleaned up and whose wordswill be wrapped across a couple lines
PassingRawDescriptionHelpFormatter asformatter_class=indicates thatdescription andepilog are already correctly formatted andshould not be line-wrapped:
>>>parser=argparse.ArgumentParser(...prog='PROG',...formatter_class=argparse.RawDescriptionHelpFormatter,...description=textwrap.dedent('''\... Please do not mess up this text!... --------------------------------... I have indented it... exactly the way... I want it... '''))>>>parser.print_help()usage: PROG [-h]Please do not mess up this text!-------------------------------- I have indented it exactly the way I want itoptional arguments: -h, --help show this help message and exit
RawTextHelpFormatter maintains whitespace for all sorts of help text,including argument descriptions. However, multiple new lines are replaced withone. If you wish to preserve multiple blank lines, add spaces between thenewlines.
ArgumentDefaultsHelpFormatter automatically adds information aboutdefault values to each of the argument help messages:
>>>parser=argparse.ArgumentParser(...prog='PROG',...formatter_class=argparse.ArgumentDefaultsHelpFormatter)>>>parser.add_argument('--foo',type=int,default=42,help='FOO!')>>>parser.add_argument('bar',nargs='*',default=[1,2,3],help='BAR!')>>>parser.print_help()usage: PROG [-h] [--foo FOO] [bar ...]positional arguments: bar BAR! (default: [1, 2, 3])optional arguments: -h, --help show this help message and exit --foo FOO FOO! (default: 42)
MetavarTypeHelpFormatter uses the name of thetype argument for eachargument as the display name for its values (rather than using thedestas the regular formatter does):
>>>parser=argparse.ArgumentParser(...prog='PROG',...formatter_class=argparse.MetavarTypeHelpFormatter)>>>parser.add_argument('--foo',type=int)>>>parser.add_argument('bar',type=float)>>>parser.print_help()usage: PROG [-h] [--foo int] floatpositional arguments: floatoptional arguments: -h, --help show this help message and exit --foo int
prefix_chars¶
Most command-line options will use- as the prefix, e.g.-f/--foo.Parsers that need to support different or additional prefixcharacters, e.g. for optionslike+f or/foo, may specify them using theprefix_chars= argumentto the ArgumentParser constructor:
>>>parser=argparse.ArgumentParser(prog='PROG',prefix_chars='-+')>>>parser.add_argument('+f')>>>parser.add_argument('++bar')>>>parser.parse_args('+f X ++bar Y'.split())Namespace(bar='Y', f='X')
Theprefix_chars= argument defaults to'-'. Supplying a set ofcharacters that does not include- will cause-f/--foo options to bedisallowed.
fromfile_prefix_chars¶
Sometimes, for example when dealing with a particularly long argument list, itmay make sense to keep the list of arguments in a file rather than typing it outat the command line. If thefromfile_prefix_chars= argument is given to theArgumentParser constructor, then arguments that start with any of thespecified characters will be treated as files, and will be replaced by thearguments they contain. For example:
>>>withopen('args.txt','w')asfp:...fp.write('-f\nbar')>>>parser=argparse.ArgumentParser(fromfile_prefix_chars='@')>>>parser.add_argument('-f')>>>parser.parse_args(['-f','foo','@args.txt'])Namespace(f='bar')
Arguments read from a file must by default be one per line (but see alsoconvert_arg_line_to_args()) and are treated as if theywere in the same place as the original file referencing argument on the commandline. So in the example above, the expression['-f','foo','@args.txt']is considered equivalent to the expression['-f','foo','-f','bar'].
Thefromfile_prefix_chars= argument defaults toNone, meaning thatarguments will never be treated as file references.
argument_default¶
Generally, argument defaults are specified either by passing a default toadd_argument() or by calling theset_defaults() methods with a specific set of name-valuepairs. Sometimes however, it may be useful to specify a single parser-widedefault for arguments. This can be accomplished by passing theargument_default= keyword argument toArgumentParser. For example,to globally suppress attribute creation onparse_args()calls, we supplyargument_default=SUPPRESS:
>>>parser=argparse.ArgumentParser(argument_default=argparse.SUPPRESS)>>>parser.add_argument('--foo')>>>parser.add_argument('bar',nargs='?')>>>parser.parse_args(['--foo','1','BAR'])Namespace(bar='BAR', foo='1')>>>parser.parse_args([])Namespace()
allow_abbrev¶
Normally, when you pass an argument list to theparse_args() method of anArgumentParser,itrecognizes abbreviations of long options.
This feature can be disabled by settingallow_abbrev toFalse:
>>>parser=argparse.ArgumentParser(prog='PROG',allow_abbrev=False)>>>parser.add_argument('--foobar',action='store_true')>>>parser.add_argument('--foonley',action='store_false')>>>parser.parse_args(['--foon'])usage: PROG [-h] [--foobar] [--foonley]PROG: error: unrecognized arguments: --foon
New in version 3.5.
conflict_handler¶
ArgumentParser objects do not allow two actions with the same optionstring. By default,ArgumentParser objects raise an exception if anattempt is made to create an argument with an option string that is already inuse:
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('-f','--foo',help='old foo help')>>>parser.add_argument('--foo',help='new foo help')Traceback (most recent call last): ..ArgumentError:argument --foo: conflicting option string(s): --foo
Sometimes (e.g. when usingparents) it may be useful to simply override anyolder arguments with the same option string. To get this behavior, the value'resolve' can be supplied to theconflict_handler= argument ofArgumentParser:
>>>parser=argparse.ArgumentParser(prog='PROG',conflict_handler='resolve')>>>parser.add_argument('-f','--foo',help='old foo help')>>>parser.add_argument('--foo',help='new foo help')>>>parser.print_help()usage: PROG [-h] [-f FOO] [--foo FOO]optional arguments: -h, --help show this help message and exit -f FOO old foo help --foo FOO new foo help
Note thatArgumentParser objects only remove an action if all of itsoption strings are overridden. So, in the example above, the old-f/--fooaction is retained as the-f action, because only the--foo optionstring was overridden.
add_help¶
By default, ArgumentParser objects add an option which simply displaysthe parser’s help message. For example, consider a file namedmyprogram.py containing the following code:
importargparseparser=argparse.ArgumentParser()parser.add_argument('--foo',help='foo help')args=parser.parse_args()
If-h or--help is supplied at the command line, the ArgumentParserhelp will be printed:
$pythonmyprogram.py--helpusage: myprogram.py [-h] [--foo FOO]optional arguments: -h, --help show this help message and exit --foo FOO foo help
Occasionally, it may be useful to disable the addition of this help option.This can be achieved by passingFalse as theadd_help= argument toArgumentParser:
>>>parser=argparse.ArgumentParser(prog='PROG',add_help=False)>>>parser.add_argument('--foo',help='foo help')>>>parser.print_help()usage: PROG [--foo FOO]optional arguments: --foo FOO foo help
The help option is typically-h/--help. The exception to this isif theprefix_chars= is specified and does not include-, inwhich case-h and--help are not valid options. Inthis case, the first character inprefix_chars is used to prefixthe help options:
>>>parser=argparse.ArgumentParser(prog='PROG',prefix_chars='+/')>>>parser.print_help()usage: PROG [+h]optional arguments: +h, ++help show this help message and exit
exit_on_error¶
Normally, when you pass an invalid argument list to theparse_args()method of anArgumentParser, it will exit with error info.
If the user would like to catch errors manually, the feature can be enabled by settingexit_on_error toFalse:
>>>parser=argparse.ArgumentParser(exit_on_error=False)>>>parser.add_argument('--integers',type=int)_StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)>>>try:...parser.parse_args('--integers a'.split())...exceptargparse.ArgumentError:...print('Catching an argumentError')...Catching an argumentError
New in version 3.9.
The add_argument() method¶
ArgumentParser.add_argument(name or flags...[,action][,nargs][,const][,default][,type][,choices][,required][,help][,metavar][,dest])¶Define how a single command-line argument should be parsed. Each parameterhas its own more detailed description below, but in short they are:
name or flags - Either a name or a list of option strings, e.g.
fooor-f,--foo.action - The basic type of action to be taken when this argument isencountered at the command line.
nargs - The number of command-line arguments that should be consumed.
const - A constant value required by someaction andnargs selections.
default - The value produced if the argument is absent from thecommand line and if it is absent from the namespace object.
type - The type to which the command-line argument should be converted.
choices - A container of the allowable values for the argument.
required - Whether or not the command-line option may be omitted(optionals only).
help - A brief description of what the argument does.
metavar - A name for the argument in usage messages.
dest - The name of the attribute to be added to the object returned by
parse_args().
The following sections describe how each of these are used.
name or flags¶
Theadd_argument() method must know whether an optionalargument, like-f or--foo, or a positional argument, like a list offilenames, is expected. The first arguments passed toadd_argument() must therefore be either a series offlags, or a simple argument name. For example, an optional argument couldbe created like:
>>>parser.add_argument('-f','--foo')
while a positional argument could be created like:
>>>parser.add_argument('bar')
Whenparse_args() is called, optional arguments will beidentified by the- prefix, and the remaining arguments will be assumed tobe positional:
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('-f','--foo')>>>parser.add_argument('bar')>>>parser.parse_args(['BAR'])Namespace(bar='BAR', foo=None)>>>parser.parse_args(['BAR','--foo','FOO'])Namespace(bar='BAR', foo='FOO')>>>parser.parse_args(['--foo','FOO'])usage: PROG [-h] [-f FOO] barPROG: error: the following arguments are required: bar
action¶
ArgumentParser objects associate command-line arguments with actions. Theseactions can do just about anything with the command-line arguments associated withthem, though most actions simply add an attribute to the object returned byparse_args(). Theaction keyword argument specifieshow the command-line arguments should be handled. The supplied actions are:
'store'- This just stores the argument’s value. This is the defaultaction. For example:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo')>>>parser.parse_args('--foo 1'.split())Namespace(foo='1')
'store_const'- This stores the value specified by theconst keywordargument. The'store_const'action is most commonly used withoptional arguments that specify some sort of flag. For example:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',action='store_const',const=42)>>>parser.parse_args(['--foo'])Namespace(foo=42)
'store_true'and'store_false'- These are special cases of'store_const'used for storing the valuesTrueandFalserespectively. In addition, they create default values ofFalseandTruerespectively. For example:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',action='store_true')>>>parser.add_argument('--bar',action='store_false')>>>parser.add_argument('--baz',action='store_false')>>>parser.parse_args('--foo --bar'.split())Namespace(foo=True, bar=False, baz=True)
'append'- This stores a list, and appends each argument value to thelist. This is useful to allow an option to be specified multiple times.Example usage:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',action='append')>>>parser.parse_args('--foo 1 --foo 2'.split())Namespace(foo=['1', '2'])
'append_const'- This stores a list, and appends the value specified bytheconst keyword argument to the list. (Note that theconst keywordargument defaults toNone.) The'append_const'action is typicallyuseful when multiple arguments need to store constants to the same list. Forexample:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--str',dest='types',action='append_const',const=str)>>>parser.add_argument('--int',dest='types',action='append_const',const=int)>>>parser.parse_args('--str --int'.split())Namespace(types=[<class 'str'>, <class 'int'>])
'count'- This counts the number of times a keyword argument occurs. Forexample, this is useful for increasing verbosity levels:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--verbose','-v',action='count',default=0)>>>parser.parse_args(['-vvv'])Namespace(verbose=3)
Note, thedefault will be
Noneunless explicitly set to0.'help'- This prints a complete help message for all the options in thecurrent parser and then exits. By default a help action is automaticallyadded to the parser. SeeArgumentParserfor details of how theoutput is created.'version'- This expects aversion=keyword argument in theadd_argument()call, and prints version informationand exits when invoked:>>>importargparse>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('--version',action='version',version='%(prog)s 2.0')>>>parser.parse_args(['--version'])PROG 2.0
'extend'- This stores a list, and extends each argument value to thelist.Example usage:>>>parser=argparse.ArgumentParser()>>>parser.add_argument("--foo",action="extend",nargs="+",type=str)>>>parser.parse_args(["--foo","f1","--foo","f2","f3","f4"])Namespace(foo=['f1', 'f2', 'f3', 'f4'])
New in version 3.8.
You may also specify an arbitrary action by passing an Action subclass orother object that implements the same interface. TheBooleanOptionalActionis available inargparse and adds support for boolean actions such as--foo and--no-foo:
>>>importargparse>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',action=argparse.BooleanOptionalAction)>>>parser.parse_args(['--no-foo'])Namespace(foo=False)
New in version 3.9.
The recommended way to create a custom action is to extendAction,overriding the__call__ method and optionally the__init__ andformat_usage methods.
An example of a custom action:
>>>classFooAction(argparse.Action):...def__init__(self,option_strings,dest,nargs=None,**kwargs):...ifnargsisnotNone:...raiseValueError("nargs not allowed")...super().__init__(option_strings,dest,**kwargs)...def__call__(self,parser,namespace,values,option_string=None):...print('%r%r%r'%(namespace,values,option_string))...setattr(namespace,self.dest,values)...>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',action=FooAction)>>>parser.add_argument('bar',action=FooAction)>>>args=parser.parse_args('1 --foo 2'.split())Namespace(bar=None, foo=None) '1' NoneNamespace(bar='1', foo=None) '2' '--foo'>>>argsNamespace(bar='1', foo='2')
For more details, seeAction.
nargs¶
ArgumentParser objects usually associate a single command-line argument with asingle action to be taken. Thenargs keyword argument associates adifferent number of command-line arguments with a single action. The supportedvalues are:
N(an integer).Narguments from the command line will be gatheredtogether into a list. For example:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',nargs=2)>>>parser.add_argument('bar',nargs=1)>>>parser.parse_args('c --foo a b'.split())Namespace(bar=['c'], foo=['a', 'b'])
Note that
nargs=1produces a list of one item. This is different fromthe default, in which the item is produced by itself.
'?'. One argument will be consumed from the command line if possible, andproduced as a single item. If no command-line argument is present, the value fromdefault will be produced. Note that for optional arguments, there is anadditional case - the option string is present but not followed by acommand-line argument. In this case the value fromconst will be produced. Someexamples to illustrate this:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',nargs='?',const='c',default='d')>>>parser.add_argument('bar',nargs='?',default='d')>>>parser.parse_args(['XX','--foo','YY'])Namespace(bar='XX', foo='YY')>>>parser.parse_args(['XX','--foo'])Namespace(bar='XX', foo='c')>>>parser.parse_args([])Namespace(bar='d', foo='d')
One of the more common uses of
nargs='?'is to allow optional input andoutput files:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('infile',nargs='?',type=argparse.FileType('r'),...default=sys.stdin)>>>parser.add_argument('outfile',nargs='?',type=argparse.FileType('w'),...default=sys.stdout)>>>parser.parse_args(['input.txt','output.txt'])Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>, outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)>>>parser.parse_args([])Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>, outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
'*'. All command-line arguments present are gathered into a list. Note thatit generally doesn’t make much sense to have more than one positional argumentwithnargs='*', but multiple optional arguments withnargs='*'ispossible. For example:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',nargs='*')>>>parser.add_argument('--bar',nargs='*')>>>parser.add_argument('baz',nargs='*')>>>parser.parse_args('a b --foo x y --bar 1 2'.split())Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
'+'. Just like'*', all command-line args present are gathered into alist. Additionally, an error message will be generated if there wasn’t atleast one command-line argument present. For example:>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('foo',nargs='+')>>>parser.parse_args(['a','b'])Namespace(foo=['a', 'b'])>>>parser.parse_args([])usage: PROG [-h] foo [foo ...]PROG: error: the following arguments are required: foo
If thenargs keyword argument is not provided, the number of arguments consumedis determined by theaction. Generally this means a single command-line argumentwill be consumed and a single item (not a list) will be produced.
const¶
Theconst argument ofadd_argument() is used to holdconstant values that are not read from the command line but are required forthe variousArgumentParser actions. The two most common uses of it are:
When
add_argument()is called withaction='store_const'oraction='append_const'. These actions add theconstvalue to one of the attributes of the object returned byparse_args(). See theaction description for examples.When
add_argument()is called with option strings(like-for--foo) andnargs='?'. This creates an optionalargument that can be followed by zero or one command-line arguments.When parsing the command line, if the option string is encountered with nocommand-line argument following it, the value ofconstwill be assumed instead.See thenargs description for examples.
With the'store_const' and'append_const' actions, theconstkeyword argument must be given. For other actions, it defaults toNone.
default¶
All optional arguments and some positional arguments may be omitted at thecommand line. Thedefault keyword argument ofadd_argument(), whose value defaults toNone,specifies what value should be used if the command-line argument is not present.For optional arguments, thedefault value is used when the option stringwas not present at the command line:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',default=42)>>>parser.parse_args(['--foo','2'])Namespace(foo='2')>>>parser.parse_args([])Namespace(foo=42)
If the target namespace already has an attribute set, the actiondefaultwill not over write it:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',default=42)>>>parser.parse_args([],namespace=argparse.Namespace(foo=101))Namespace(foo=101)
If thedefault value is a string, the parser parses the value as if itwere a command-line argument. In particular, the parser applies anytypeconversion argument, if provided, before setting the attribute on theNamespace return value. Otherwise, the parser uses the value as is:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--length',default='10',type=int)>>>parser.add_argument('--width',default=10.5,type=int)>>>parser.parse_args()Namespace(length=10, width=10.5)
For positional arguments withnargs equal to? or*, thedefault valueis used when no command-line argument was present:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('foo',nargs='?',default=42)>>>parser.parse_args(['a'])Namespace(foo='a')>>>parser.parse_args([])Namespace(foo=42)
Providingdefault=argparse.SUPPRESS causes no attribute to be added if thecommand-line argument was not present:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',default=argparse.SUPPRESS)>>>parser.parse_args([])Namespace()>>>parser.parse_args(['--foo','1'])Namespace(foo='1')
type¶
By default, the parser reads command-line arguments in as simplestrings. However, quite often the command-line string should instead beinterpreted as another type, such as afloat orint. Thetype keyword foradd_argument() allows anynecessary type-checking and type conversions to be performed.
If thetype keyword is used with thedefault keyword, the type converteris only applied if the default is a string.
The argument totype can be any callable that accepts a single string.If the function raisesArgumentTypeError,TypeError, orValueError, the exception is caught and a nicely formatted errormessage is displayed. No other exception types are handled.
Common built-in types and functions can be used as type converters:
importargparseimportpathlibparser=argparse.ArgumentParser()parser.add_argument('count',type=int)parser.add_argument('distance',type=float)parser.add_argument('street',type=ascii)parser.add_argument('code_point',type=ord)parser.add_argument('source_file',type=open)parser.add_argument('dest_file',type=argparse.FileType('w',encoding='latin-1'))parser.add_argument('datapath',type=pathlib.Path)
User defined functions can be used as well:
>>>defhyphenated(string):...return'-'.join([word[:4]forwordinstring.casefold().split()])...>>>parser=argparse.ArgumentParser()>>>_=parser.add_argument('short_title',type=hyphenated)>>>parser.parse_args(['"The Tale of Two Cities"'])Namespace(short_title='"the-tale-of-two-citi')
Thebool() function is not recommended as a type converter. All it doesis convert empty strings toFalse and non-empty strings toTrue.This is usually not what is desired.
In general, thetype keyword is a convenience that should only be used forsimple conversions that can only raise one of the three supported exceptions.Anything with more interesting error-handling or resource management should bedone downstream after the arguments are parsed.
For example, JSON or YAML conversions have complex error cases that requirebetter reporting than can be given by thetype keyword. AJSONDecodeError would not be well formatted and aFileNotFound exception would not be handled at all.
EvenFileType has its limitations for use with thetypekeyword. If one argument usesFileType and then a subsequent argument fails,an error is reported but the file is not automatically closed. In this case, itwould be better to wait until after the parser has run and then use thewith-statement to manage the files.
For type checkers that simply check against a fixed set of values, considerusing thechoices keyword instead.
choices¶
Some command-line arguments should be selected from a restricted set of values.These can be handled by passing a container object as thechoices keywordargument toadd_argument(). When the command line isparsed, argument values will be checked, and an error message will be displayedif the argument was not one of the acceptable values:
>>>parser=argparse.ArgumentParser(prog='game.py')>>>parser.add_argument('move',choices=['rock','paper','scissors'])>>>parser.parse_args(['rock'])Namespace(move='rock')>>>parser.parse_args(['fire'])usage: game.py [-h] {rock,paper,scissors}game.py: error: argument move: invalid choice: 'fire' (choose from 'rock','paper', 'scissors')
Note that inclusion in thechoices container is checked after anytypeconversions have been performed, so the type of the objects in thechoicescontainer should match thetype specified:
>>>parser=argparse.ArgumentParser(prog='doors.py')>>>parser.add_argument('door',type=int,choices=range(1,4))>>>print(parser.parse_args(['3']))Namespace(door=3)>>>parser.parse_args(['4'])usage: doors.py [-h] {1,2,3}doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Any container can be passed as thechoices value, solist objects,set objects, and custom containers are all supported.
Use ofenum.Enum is not recommended because it is difficult tocontrol its appearance in usage, help, and error messages.
Formatted choices overrides the defaultmetavar which is normally derivedfromdest. This is usually what you want because the user never sees thedest parameter. If this display isn’t desirable (perhaps because there aremany choices), just specify an explicitmetavar.
required¶
In general, theargparse module assumes that flags like-f and--barindicateoptional arguments, which can always be omitted at the command line.To make an optionrequired,True can be specified for therequired=keyword argument toadd_argument():
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',required=True)>>>parser.parse_args(['--foo','BAR'])Namespace(foo='BAR')>>>parser.parse_args([])usage: [-h] --foo FOO: error: the following arguments are required: --foo
As the example shows, if an option is marked asrequired,parse_args() will report an error if that option is notpresent at the command line.
Note
Required options are generally considered bad form because users expectoptions to beoptional, and thus they should be avoided when possible.
help¶
Thehelp value is a string containing a brief description of the argument.When a user requests help (usually by using-h or--help at thecommand line), thesehelp descriptions will be displayed with eachargument:
>>>parser=argparse.ArgumentParser(prog='frobble')>>>parser.add_argument('--foo',action='store_true',...help='foo the bars before frobbling')>>>parser.add_argument('bar',nargs='+',...help='one of the bars to be frobbled')>>>parser.parse_args(['-h'])usage: frobble [-h] [--foo] bar [bar ...]positional arguments: bar one of the bars to be frobbledoptional arguments: -h, --help show this help message and exit --foo foo the bars before frobbling
Thehelp strings can include various format specifiers to avoid repetitionof things like the program name or the argumentdefault. The availablespecifiers include the program name,%(prog)s and most keyword arguments toadd_argument(), e.g.%(default)s,%(type)s, etc.:
>>>parser=argparse.ArgumentParser(prog='frobble')>>>parser.add_argument('bar',nargs='?',type=int,default=42,...help='the bar to%(prog)s (default:%(default)s)')>>>parser.print_help()usage: frobble [-h] [bar]positional arguments: bar the bar to frobble (default: 42)optional arguments: -h, --help show this help message and exit
As the help string supports %-formatting, if you want a literal% to appearin the help string, you must escape it as%%.
argparse supports silencing the help entry for certain options, bysetting thehelp value toargparse.SUPPRESS:
>>>parser=argparse.ArgumentParser(prog='frobble')>>>parser.add_argument('--foo',help=argparse.SUPPRESS)>>>parser.print_help()usage: frobble [-h]optional arguments: -h, --help show this help message and exit
metavar¶
WhenArgumentParser generates help messages, it needs some way to referto each expected argument. By default, ArgumentParser objects use thedestvalue as the “name” of each object. By default, for positional argumentactions, thedest value is used directly, and for optional argument actions,thedest value is uppercased. So, a single positional argument withdest='bar' will be referred to asbar. A singleoptional argument--foo that should be followed by a single command-line argumentwill be referred to asFOO. An example:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo')>>>parser.add_argument('bar')>>>parser.parse_args('X --foo Y'.split())Namespace(bar='X', foo='Y')>>>parser.print_help()usage: [-h] [--foo FOO] barpositional arguments: baroptional arguments: -h, --help show this help message and exit --foo FOO
An alternative name can be specified withmetavar:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',metavar='YYY')>>>parser.add_argument('bar',metavar='XXX')>>>parser.parse_args('X --foo Y'.split())Namespace(bar='X', foo='Y')>>>parser.print_help()usage: [-h] [--foo YYY] XXXpositional arguments: XXXoptional arguments: -h, --help show this help message and exit --foo YYY
Note thatmetavar only changes thedisplayed name - the name of theattribute on theparse_args() object is still determinedby thedest value.
Different values ofnargs may cause the metavar to be used multiple times.Providing a tuple tometavar specifies a different display for each of thearguments:
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('-x',nargs=2)>>>parser.add_argument('--foo',nargs=2,metavar=('bar','baz'))>>>parser.print_help()usage: PROG [-h] [-x X X] [--foo bar baz]optional arguments: -h, --help show this help message and exit -x X X --foo bar baz
dest¶
MostArgumentParser actions add some value as an attribute of theobject returned byparse_args(). The name of thisattribute is determined by thedest keyword argument ofadd_argument(). For positional argument actions,dest is normally supplied as the first argument toadd_argument():
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('bar')>>>parser.parse_args(['XXX'])Namespace(bar='XXX')
For optional argument actions, the value ofdest is normally inferred fromthe option strings.ArgumentParser generates the value ofdest bytaking the first long option string and stripping away the initial--string. If no long option strings were supplied,dest will be derived fromthe first short option string by stripping the initial- character. Anyinternal- characters will be converted to_ characters to make surethe string is a valid attribute name. The examples below illustrate thisbehavior:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('-f','--foo-bar','--foo')>>>parser.add_argument('-x','-y')>>>parser.parse_args('-f 1 -x 2'.split())Namespace(foo_bar='1', x='2')>>>parser.parse_args('--foo 1 -y 2'.split())Namespace(foo_bar='1', x='2')
dest allows a custom attribute name to be provided:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',dest='bar')>>>parser.parse_args('--foo XXX'.split())Namespace(bar='XXX')
Action classes¶
Action classes implement the Action API, a callable which returns a callablewhich processes arguments from the command-line. Any object which followsthis API may be passed as theaction parameter toadd_argument().
- class
argparse.Action(option_strings,dest,nargs=None,const=None,default=None,type=None,choices=None,required=False,help=None,metavar=None)¶
Action objects are used by an ArgumentParser to represent the informationneeded to parse a single argument from one or more strings from thecommand line. The Action class must accept the two positional argumentsplus any keyword arguments passed toArgumentParser.add_argument()except for theaction itself.
Instances of Action (or return value of any callable to theactionparameter) should have attributes “dest”, “option_strings”, “default”, “type”,“required”, “help”, etc. defined. The easiest way to ensure these attributesare defined is to callAction.__init__.
Action instances should be callable, so subclasses must override the__call__ method, which should accept four parameters:
parser- The ArgumentParser object which contains this action.namespace- TheNamespaceobject that will be returned byparse_args(). Most actions add an attribute to thisobject usingsetattr().values- The associated command-line arguments, with any type conversionsapplied. Type conversions are specified with thetype keyword argument toadd_argument().option_string- The option string that was used to invoke this action.Theoption_stringargument is optional, and will be absent if the actionis associated with a positional argument.
The__call__ method may perform arbitrary actions, but will typically setattributes on thenamespace based ondest andvalues.
Action subclasses can define aformat_usage method that takes no argumentand return a string which will be used when printing the usage of the program.If such method is not provided, a sensible default will be used.
The parse_args() method¶
ArgumentParser.parse_args(args=None,namespace=None)¶Convert argument strings to objects and assign them as attributes of thenamespace. Return the populated namespace.
Previous calls to
add_argument()determine exactly what objects arecreated and how they are assigned. See the documentation foradd_argument()for details.
Option value syntax¶
Theparse_args() method supports several ways ofspecifying the value of an option (if it takes one). In the simplest case, theoption and its value are passed as two separate arguments:
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('-x')>>>parser.add_argument('--foo')>>>parser.parse_args(['-x','X'])Namespace(foo=None, x='X')>>>parser.parse_args(['--foo','FOO'])Namespace(foo='FOO', x=None)
For long options (options with names longer than a single character), the optionand value can also be passed as a single command-line argument, using= toseparate them:
>>>parser.parse_args(['--foo=FOO'])Namespace(foo='FOO', x=None)
For short options (options only one character long), the option and its valuecan be concatenated:
>>>parser.parse_args(['-xX'])Namespace(foo=None, x='X')
Several short options can be joined together, using only a single- prefix,as long as only the last option (or none of them) requires a value:
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('-x',action='store_true')>>>parser.add_argument('-y',action='store_true')>>>parser.add_argument('-z')>>>parser.parse_args(['-xyzZ'])Namespace(x=True, y=True, z='Z')
Invalid arguments¶
While parsing the command line,parse_args() checks for avariety of errors, including ambiguous options, invalid types, invalid options,wrong number of positional arguments, etc. When it encounters such an error,it exits and prints the error along with a usage message:
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('--foo',type=int)>>>parser.add_argument('bar',nargs='?')>>># invalid type>>>parser.parse_args(['--foo','spam'])usage: PROG [-h] [--foo FOO] [bar]PROG: error: argument --foo: invalid int value: 'spam'>>># invalid option>>>parser.parse_args(['--bar'])usage: PROG [-h] [--foo FOO] [bar]PROG: error: no such option: --bar>>># wrong number of arguments>>>parser.parse_args(['spam','badger'])usage: PROG [-h] [--foo FOO] [bar]PROG: error: extra arguments found: badger
Arguments containing-¶
Theparse_args() method attempts to give errors wheneverthe user has clearly made a mistake, but some situations are inherentlyambiguous. For example, the command-line argument-1 could either be anattempt to specify an option or an attempt to provide a positional argument.Theparse_args() method is cautious here: positionalarguments may only begin with- if they look like negative numbers andthere are no options in the parser that look like negative numbers:
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('-x')>>>parser.add_argument('foo',nargs='?')>>># no negative number options, so -1 is a positional argument>>>parser.parse_args(['-x','-1'])Namespace(foo=None, x='-1')>>># no negative number options, so -1 and -5 are positional arguments>>>parser.parse_args(['-x','-1','-5'])Namespace(foo='-5', x='-1')>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('-1',dest='one')>>>parser.add_argument('foo',nargs='?')>>># negative number options present, so -1 is an option>>>parser.parse_args(['-1','X'])Namespace(foo=None, one='X')>>># negative number options present, so -2 is an option>>>parser.parse_args(['-2'])usage: PROG [-h] [-1 ONE] [foo]PROG: error: no such option: -2>>># negative number options present, so both -1s are options>>>parser.parse_args(['-1','-1'])usage: PROG [-h] [-1 ONE] [foo]PROG: error: argument -1: expected one argument
If you have positional arguments that must begin with- and don’t looklike negative numbers, you can insert the pseudo-argument'--' which tellsparse_args() that everything after that is a positionalargument:
>>>parser.parse_args(['--','-f'])Namespace(foo='-f', one=None)
Argument abbreviations (prefix matching)¶
Theparse_args() methodby defaultallows long options to be abbreviated to a prefix, if the abbreviation isunambiguous (the prefix matches a unique option):
>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('-bacon')>>>parser.add_argument('-badger')>>>parser.parse_args('-bac MMM'.split())Namespace(bacon='MMM', badger=None)>>>parser.parse_args('-bad WOOD'.split())Namespace(bacon=None, badger='WOOD')>>>parser.parse_args('-ba BA'.split())usage: PROG [-h] [-bacon BACON] [-badger BADGER]PROG: error: ambiguous option: -ba could match -badger, -bacon
An error is produced for arguments that could produce more than one options.This feature can be disabled by settingallow_abbrev toFalse.
Beyondsys.argv¶
Sometimes it may be useful to have an ArgumentParser parse arguments other than thoseofsys.argv. This can be accomplished by passing a list of strings toparse_args(). This is useful for testing at theinteractive prompt:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument(...'integers',metavar='int',type=int,choices=range(10),...nargs='+',help='an integer in the range 0..9')>>>parser.add_argument(...'--sum',dest='accumulate',action='store_const',const=sum,...default=max,help='sum the integers (default: find the max)')>>>parser.parse_args(['1','2','3','4'])Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])>>>parser.parse_args(['1','2','3','4','--sum'])Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
The Namespace object¶
- class
argparse.Namespace¶ Simple class used by default by
parse_args()to createan object holding attributes and return it.
This class is deliberately simple, just anobject subclass with areadable string representation. If you prefer to have dict-like view of theattributes, you can use the standard Python idiom,vars():
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo')>>>args=parser.parse_args(['--foo','BAR'])>>>vars(args){'foo': 'BAR'}
It may also be useful to have anArgumentParser assign attributes to analready existing object, rather than a newNamespace object. This canbe achieved by specifying thenamespace= keyword argument:
>>>classC:...pass...>>>c=C()>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo')>>>parser.parse_args(args=['--foo','BAR'],namespace=c)>>>c.foo'BAR'
Other utilities¶
Sub-commands¶
ArgumentParser.add_subparsers([title][,description][,prog][,parser_class][,action][,option_string][,dest][,required][,help][,metavar])¶Many programs split up their functionality into a number of sub-commands,for example, the
svnprogram can invoke sub-commands likesvncheckout,svnupdate, andsvncommit. Splitting up functionalitythis way can be a particularly good idea when a program performs severaldifferent functions which require different kinds of command-line arguments.ArgumentParsersupports the creation of such sub-commands with theadd_subparsers()method. Theadd_subparsers()method is normallycalled with no arguments and returns a special action object. This objecthas a single method,add_parser(), which takes acommand name and anyArgumentParserconstructor arguments, andreturns anArgumentParserobject that can be modified as usual.Description of parameters:
title - title for the sub-parser group in help output; by default“subcommands” if description is provided, otherwise uses title forpositional arguments
description - description for the sub-parser group in help output, bydefault
Noneprog - usage information that will be displayed with sub-command help,by default the name of the program and any positional arguments before thesubparser argument
parser_class - class which will be used to create sub-parser instances, bydefault the class of the current parser (e.g. ArgumentParser)
action - the basic type of action to be taken when this argument isencountered at the command line
dest - name of the attribute under which sub-command name will bestored; by default
Noneand no value is storedrequired - Whether or not a subcommand must be provided, by default
False(added in 3.7)help - help for sub-parser group in help output, by default
Nonemetavar - string presenting available sub-commands in help; by default itis
Noneand presents sub-commands in form {cmd1, cmd2, ..}
Some example usage:
>>># create the top-level parser>>>parser=argparse.ArgumentParser(prog='PROG')>>>parser.add_argument('--foo',action='store_true',help='foo help')>>>subparsers=parser.add_subparsers(help='sub-command help')>>>>>># create the parser for the "a" command>>>parser_a=subparsers.add_parser('a',help='a help')>>>parser_a.add_argument('bar',type=int,help='bar help')>>>>>># create the parser for the "b" command>>>parser_b=subparsers.add_parser('b',help='b help')>>>parser_b.add_argument('--baz',choices='XYZ',help='baz help')>>>>>># parse some argument lists>>>parser.parse_args(['a','12'])Namespace(bar=12, foo=False)>>>parser.parse_args(['--foo','b','--baz','Z'])Namespace(baz='Z', foo=True)
Note that the object returned by
parse_args()will only containattributes for the main parser and the subparser that was selected by thecommand line (and not any other subparsers). So in the example above, whentheacommand is specified, only thefooandbarattributes arepresent, and when thebcommand is specified, only thefooandbazattributes are present.Similarly, when a help message is requested from a subparser, only the helpfor that particular parser will be printed. The help message will notinclude parent parser or sibling parser messages. (A help message for eachsubparser command, however, can be given by supplying the
help=argumenttoadd_parser()as above.)>>>parser.parse_args(['--help'])usage: PROG [-h] [--foo] {a,b} ...positional arguments: {a,b} sub-command help a a help b b helpoptional arguments: -h, --help show this help message and exit --foo foo help>>>parser.parse_args(['a','--help'])usage: PROG a [-h] barpositional arguments: bar bar helpoptional arguments: -h, --help show this help message and exit>>>parser.parse_args(['b','--help'])usage: PROG b [-h] [--baz {X,Y,Z}]optional arguments: -h, --help show this help message and exit --baz {X,Y,Z} baz help
The
add_subparsers()method also supportstitleanddescriptionkeyword arguments. When either is present, the subparser’s commands willappear in their own group in the help output. For example:>>>parser=argparse.ArgumentParser()>>>subparsers=parser.add_subparsers(title='subcommands',...description='valid subcommands',...help='additional help')>>>subparsers.add_parser('foo')>>>subparsers.add_parser('bar')>>>parser.parse_args(['-h'])usage: [-h] {foo,bar} ...optional arguments: -h, --help show this help message and exitsubcommands: valid subcommands {foo,bar} additional help
Furthermore,
add_parsersupports an additionalaliasesargument,which allows multiple strings to refer to the same subparser. This example,likesvn, aliasescoas a shorthand forcheckout:>>>parser=argparse.ArgumentParser()>>>subparsers=parser.add_subparsers()>>>checkout=subparsers.add_parser('checkout',aliases=['co'])>>>checkout.add_argument('foo')>>>parser.parse_args(['co','bar'])Namespace(foo='bar')
One particularly effective way of handling sub-commands is to combine the useof the
add_subparsers()method with calls toset_defaults()sothat each subparser knows which Python function it should execute. Forexample:>>># sub-command functions>>>deffoo(args):...print(args.x*args.y)...>>>defbar(args):...print('((%s))'%args.z)...>>># create the top-level parser>>>parser=argparse.ArgumentParser()>>>subparsers=parser.add_subparsers()>>>>>># create the parser for the "foo" command>>>parser_foo=subparsers.add_parser('foo')>>>parser_foo.add_argument('-x',type=int,default=1)>>>parser_foo.add_argument('y',type=float)>>>parser_foo.set_defaults(func=foo)>>>>>># create the parser for the "bar" command>>>parser_bar=subparsers.add_parser('bar')>>>parser_bar.add_argument('z')>>>parser_bar.set_defaults(func=bar)>>>>>># parse the args and call whatever function was selected>>>args=parser.parse_args('foo 1 -x 2'.split())>>>args.func(args)2.0>>>>>># parse the args and call whatever function was selected>>>args=parser.parse_args('bar XYZYX'.split())>>>args.func(args)((XYZYX))
This way, you can let
parse_args()do the job of calling theappropriate function after argument parsing is complete. Associatingfunctions with actions like this is typically the easiest way to handle thedifferent actions for each of your subparsers. However, if it is necessaryto check the name of the subparser that was invoked, thedestkeywordargument to theadd_subparsers()call will work:>>>parser=argparse.ArgumentParser()>>>subparsers=parser.add_subparsers(dest='subparser_name')>>>subparser1=subparsers.add_parser('1')>>>subparser1.add_argument('-x')>>>subparser2=subparsers.add_parser('2')>>>subparser2.add_argument('y')>>>parser.parse_args(['2','frobble'])Namespace(subparser_name='2', y='frobble')
Changed in version 3.7:Newrequired keyword argument.
FileType objects¶
- class
argparse.FileType(mode='r',bufsize=-1,encoding=None,errors=None)¶ The
FileTypefactory creates objects that can be passed to the typeargument ofArgumentParser.add_argument(). Arguments that haveFileTypeobjects as their type will open command-line arguments asfiles with the requested modes, buffer sizes, encodings and error handling(see theopen()function for more details):>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--raw',type=argparse.FileType('wb',0))>>>parser.add_argument('out',type=argparse.FileType('w',encoding='UTF-8'))>>>parser.parse_args(['--raw','raw.dat','file.txt'])Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)
FileType objects understand the pseudo-argument
'-'and automaticallyconvert this intosys.stdinfor readableFileTypeobjects andsys.stdoutfor writableFileTypeobjects:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('infile',type=argparse.FileType('r'))>>>parser.parse_args(['-'])Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
New in version 3.4:Theencodings anderrors keyword arguments.
Argument groups¶
ArgumentParser.add_argument_group(title=None,description=None)¶By default,
ArgumentParsergroups command-line arguments into“positional arguments” and “optional arguments” when displaying helpmessages. When there is a better conceptual grouping of arguments than thisdefault one, appropriate groups can be created using theadd_argument_group()method:>>>parser=argparse.ArgumentParser(prog='PROG',add_help=False)>>>group=parser.add_argument_group('group')>>>group.add_argument('--foo',help='foo help')>>>group.add_argument('bar',help='bar help')>>>parser.print_help()usage: PROG [--foo FOO] bargroup: bar bar help --foo FOO foo help
The
add_argument_group()method returns an argument group object whichhas anadd_argument()method just like a regularArgumentParser. When an argument is added to the group, the parsertreats it just like a normal argument, but displays the argument in aseparate group for help messages. Theadd_argument_group()methodacceptstitle anddescription arguments which can be used tocustomize this display:>>>parser=argparse.ArgumentParser(prog='PROG',add_help=False)>>>group1=parser.add_argument_group('group1','group1 description')>>>group1.add_argument('foo',help='foo help')>>>group2=parser.add_argument_group('group2','group2 description')>>>group2.add_argument('--bar',help='bar help')>>>parser.print_help()usage: PROG [--bar BAR] foogroup1: group1 description foo foo helpgroup2: group2 description --bar BAR bar help
Note that any arguments not in your user-defined groups will end up backin the usual “positional arguments” and “optional arguments” sections.
Mutual exclusion¶
ArgumentParser.add_mutually_exclusive_group(required=False)¶Create a mutually exclusive group.
argparsewill make sure that onlyone of the arguments in the mutually exclusive group was present on thecommand line:>>>parser=argparse.ArgumentParser(prog='PROG')>>>group=parser.add_mutually_exclusive_group()>>>group.add_argument('--foo',action='store_true')>>>group.add_argument('--bar',action='store_false')>>>parser.parse_args(['--foo'])Namespace(bar=True, foo=True)>>>parser.parse_args(['--bar'])Namespace(bar=False, foo=False)>>>parser.parse_args(['--foo','--bar'])usage: PROG [-h] [--foo | --bar]PROG: error: argument --bar: not allowed with argument --foo
The
add_mutually_exclusive_group()method also accepts arequiredargument, to indicate that at least one of the mutually exclusive argumentsis required:>>>parser=argparse.ArgumentParser(prog='PROG')>>>group=parser.add_mutually_exclusive_group(required=True)>>>group.add_argument('--foo',action='store_true')>>>group.add_argument('--bar',action='store_false')>>>parser.parse_args([])usage: PROG [-h] (--foo | --bar)PROG: error: one of the arguments --foo --bar is required
Note that currently mutually exclusive argument groups do not support thetitle anddescription arguments of
add_argument_group().
Parser defaults¶
ArgumentParser.set_defaults(**kwargs)¶Most of the time, the attributes of the object returned by
parse_args()will be fully determined by inspecting the command-line arguments and the argumentactions.set_defaults()allows some additionalattributes that are determined without any inspection of the command line tobe added:>>>parser=argparse.ArgumentParser()>>>parser.add_argument('foo',type=int)>>>parser.set_defaults(bar=42,baz='badger')>>>parser.parse_args(['736'])Namespace(bar=42, baz='badger', foo=736)
Note that parser-level defaults always override argument-level defaults:
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',default='bar')>>>parser.set_defaults(foo='spam')>>>parser.parse_args([])Namespace(foo='spam')
Parser-level defaults can be particularly useful when working with multipleparsers. See the
add_subparsers()method for anexample of this type.
ArgumentParser.get_default(dest)¶Get the default value for a namespace attribute, as set by either
add_argument()or byset_defaults():>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',default='badger')>>>parser.get_default('foo')'badger'
Printing help¶
In most typical applications,parse_args() will takecare of formatting and printing any usage or error messages. However, severalformatting methods are available:
ArgumentParser.print_usage(file=None)¶Print a brief description of how the
ArgumentParsershould beinvoked on the command line. Iffile isNone,sys.stdoutisassumed.
ArgumentParser.print_help(file=None)¶Print a help message, including the program usage and information about thearguments registered with the
ArgumentParser. Iffile isNone,sys.stdoutis assumed.
There are also variants of these methods that simply return a string instead ofprinting it:
ArgumentParser.format_usage()¶Return a string containing a brief description of how the
ArgumentParsershould be invoked on the command line.
ArgumentParser.format_help()¶Return a string containing a help message, including the program usage andinformation about the arguments registered with the
ArgumentParser.
Partial parsing¶
ArgumentParser.parse_known_args(args=None,namespace=None)¶
Sometimes a script may only parse a few of the command-line arguments, passingthe remaining arguments on to another script or program. In these cases, theparse_known_args() method can be useful. It works much likeparse_args() except that it does not produce an error whenextra arguments are present. Instead, it returns a two item tuple containingthe populated namespace and the list of remaining argument strings.
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo',action='store_true')>>>parser.add_argument('bar')>>>parser.parse_known_args(['--foo','--badger','BAR','spam'])(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
Warning
Prefix matching rules apply toparse_known_args(). The parser may consume an option even if it’s justa prefix of one of its known options, instead of leaving it in the remainingarguments list.
Customizing file parsing¶
ArgumentParser.convert_arg_line_to_args(arg_line)¶Arguments that are read from a file (see thefromfile_prefix_charskeyword argument to the
ArgumentParserconstructor) are read oneargument per line.convert_arg_line_to_args()can be overridden forfancier reading.This method takes a single argumentarg_line which is a string read fromthe argument file. It returns a list of arguments parsed from this string.The method is called once per line read from the argument file, in order.
A useful override of this method is one that treats each space-separated wordas an argument. The following example demonstrates how to do this:
classMyArgumentParser(argparse.ArgumentParser):defconvert_arg_line_to_args(self,arg_line):returnarg_line.split()
Exiting methods¶
ArgumentParser.exit(status=0,message=None)¶This method terminates the program, exiting with the specifiedstatusand, if given, it prints amessage before that. The user can overridethis method to handle these steps differently:
classErrorCatchingArgumentParser(argparse.ArgumentParser):defexit(self,status=0,message=None):ifstatus:raiseException(f'Exiting because of an error:{message}')exit(status)
ArgumentParser.error(message)¶This method prints a usage message including themessage to thestandard error and terminates the program with a status code of 2.
Intermixed parsing¶
ArgumentParser.parse_intermixed_args(args=None,namespace=None)¶
ArgumentParser.parse_known_intermixed_args(args=None,namespace=None)¶
A number of Unix commands allow the user to intermix optional arguments withpositional arguments. Theparse_intermixed_args()andparse_known_intermixed_args() methodssupport this parsing style.
These parsers do not support all the argparse features, and will raiseexceptions if unsupported features are used. In particular, subparsers,argparse.REMAINDER, and mutually exclusive groups that include bothoptionals and positionals are not supported.
The following example shows the difference betweenparse_known_args() andparse_intermixed_args(): the former returns['2','3'] as unparsed arguments, while the latter collects all the positionalsintorest.
>>>parser=argparse.ArgumentParser()>>>parser.add_argument('--foo')>>>parser.add_argument('cmd')>>>parser.add_argument('rest',nargs='*',type=int)>>>parser.parse_known_args('doit 1 --foo bar 2 3'.split())(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])>>>parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])
parse_known_intermixed_args() returns a two item tuplecontaining the populated namespace and the list of remaining argument strings.parse_intermixed_args() raises an error if there are anyremaining unparsed argument strings.
New in version 3.7.
Upgrading optparse code¶
Originally, theargparse module had attempted to maintain compatibilitywithoptparse. However,optparse was difficult to extendtransparently, particularly with the changes required to support the newnargs= specifiers and better usage messages. When most everything inoptparse had either been copy-pasted over or monkey-patched, it nolonger seemed practical to try to maintain the backwards compatibility.
Theargparse module improves on the standard libraryoptparsemodule in a number of ways including:
Handling positional arguments.
Supporting sub-commands.
Allowing alternative option prefixes like
+and/.Handling zero-or-more and one-or-more style arguments.
Producing more informative usage messages.
Providing a much simpler interface for custom
typeandaction.
A partial upgrade path fromoptparse toargparse:
Replace all
optparse.OptionParser.add_option()calls withArgumentParser.add_argument()calls.Replace
(options,args)=parser.parse_args()withargs=parser.parse_args()and add additionalArgumentParser.add_argument()calls for the positional arguments. Keep in mind that what was previouslycalledoptions, now in theargparsecontext is calledargs.Replace
optparse.OptionParser.disable_interspersed_args()by usingparse_intermixed_args()instead ofparse_args().Replace callback actions and the
callback_*keyword arguments withtypeoractionarguments.Replace string names for
typekeyword arguments with the correspondingtype objects (e.g. int, float, complex, etc).Replace
optparse.ValueswithNamespaceandoptparse.OptionErrorandoptparse.OptionValueErrorwithArgumentError.Replace strings with implicit arguments such as
%defaultor%progwiththe standard Python syntax to use dictionaries to format strings, that is,%(default)sand%(prog)s.Replace the OptionParser constructor
versionargument with a call toparser.add_argument('--version',action='version',version='<theversion>').