Source code: Lib/argparse.py

This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the argparse tutorial .

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv . The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv .

ArgumentParser parses arguments through the parse_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 simple Namespace object will be built up from attributes parsed out of the command line:

Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

Filling an ArgumentParser with information about program arguments is done by making calls to the add_argument() method. Generally, these calls tell the ArgumentParser how to take the strings on the command line and turn them into objects. This information is stored and used when parse_args() is called. For example:

The ArgumentParser object will hold all the information necessary to parse the command line into Python data types.

The first step in using the argparse is creating an ArgumentParser object:

The following sections walk you through this example.

If invalid arguments are passed in, it will issue an error:

When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:

-h, --help show this help message and exit

Assuming the Python code above is saved into a file called prog.py , it can be run at the command line and provides useful help messages:

The following code is a Python program that takes a list of integers and produces either the sum or the max:

If the user would like catch errors manually, the feature can be enable by setting exit_on_error to False :

Normally, when you pass an invalid argument list to the parse_args() method of an ArgumentParser , it will exit with error info.

+h, ++help show this help message and exit

The help option is typically -h/--help . The exception to this is if the prefix_chars= is specified and does not include - , in which case -h and --help are not valid options. In this case, the first character in prefix_chars is used to prefix the help options:

Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing False as the add_help= argument to ArgumentParser :

-h, --help show this help message and exit

If -h or --help is supplied at the command line, the ArgumentParser help will be printed:

By default, ArgumentParser objects add an option which simply displays the parser’s help message. For example, consider a file named myprogram.py containing the following code:

Note that ArgumentParser objects only remove an action if all of its option strings are overridden. So, in the example above, the old -f/--foo action is retained as the -f action, because only the --foo option string was overridden.

-h, --help show this help message and exit

Sometimes (e.g. when using parents ) it may be useful to simply override any older arguments with the same option string. To get this behavior, the value 'resolve' can be supplied to the conflict_handler= argument of ArgumentParser :

ArgumentParser objects do not allow two actions with the same option string. By default, ArgumentParser objects raise an exception if an attempt is made to create an argument with an option string that is already in use:

This feature can be disabled by setting allow_abbrev to False :

Normally, when you pass an argument list to the parse_args() method of an ArgumentParser , it recognizes abbreviations of long options.

Generally, argument defaults are specified either by passing a default to add_argument() or by calling the set_defaults() methods with a specific set of name-value pairs. Sometimes however, it may be useful to specify a single parser-wide default for arguments. This can be accomplished by passing the argument_default= keyword argument to ArgumentParser . For example, to globally suppress attribute creation on parse_args() calls, we supply argument_default=SUPPRESS :

The fromfile_prefix_chars= argument defaults to None , meaning that arguments will never be treated as file references.

Arguments read from a file must by default be one per line (but see also convert_arg_line_to_args() ) and are treated as if they were in the same place as the original file referencing argument on the command line. So in the example above, the expression ['-f', 'foo', '@args.txt'] is considered equivalent to the expression ['-f', 'foo', '-f', 'bar'] .

Sometimes, for example when dealing with a particularly long argument lists, it may make sense to keep the list of arguments in a file rather than typing it out at the command line. If the fromfile_prefix_chars= argument is given to the ArgumentParser constructor, then arguments that start with any of the specified characters will be treated as files, and will be replaced by the arguments they contain. For example:

The prefix_chars= argument defaults to '-' . Supplying a set of characters that does not include - will cause -f/--foo options to be disallowed.

Most command-line options will use - as the prefix, e.g. -f/--foo . Parsers that need to support different or additional prefix characters, e.g. for options like +f or /foo , may specify them using the prefix_chars= argument to the ArgumentParser constructor:

-h, --help show this help message and exit

MetavarTypeHelpFormatter uses the name of the type argument for each argument as the display name for its values (rather than using the dest as the regular formatter does):

-h, --help show this help message and exit

ArgumentDefaultsHelpFormatter automatically adds information about default values to each of the argument help messages:

RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions. However, multiple new lines are replaced with one. If you wish to preserve multiple blank lines, add spaces between the newlines.

-h, --help show this help message and exit

Please do not mess up this text!

Please do not mess up this text!

Passing RawDescriptionHelpFormatter as formatter_class= indicates that description and epilog are already correctly formatted and should not be line-wrapped:

likewise for this epilog whose whitespace will be cleaned up and whose words

-h, --help show this help message and exit

this description was indented weird but that is okay

be cleaned up and whose words will be wrapped

likewise for this epilog whose whitespace will

but that is okay'''

RawDescriptionHelpFormatter and RawTextHelpFormatter give more control over how textual descriptions are displayed. By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages:

ArgumentParser objects allow the help formatting to be customized by specifying an alternate formatting class. Currently, there are four such classes:

You must fully initialize the parsers before passing them via parents= . If you change the parent parsers after the child parser, those changes will not be reflected in the child.

Note that most parent parsers will specify add_help=False . Otherwise, the ArgumentParser will see two -h/--help options (one in the parent and one in the child) and raise an error.

Sometimes, several parsers share a common set of arguments. Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to parents= argument to ArgumentParser can be used. The parents= argument takes a list of ArgumentParser objects, collects all the positional and optional actions from them, and adds these actions to the ArgumentParser object being constructed:

As with the description argument, the epilog= text is by default line-wrapped, but this behavior can be adjusted with the formatter_class argument to ArgumentParser .

-h, --help show this help message and exit

Some programs like to display additional description of the program after the description of the arguments. Such text can be specified using the epilog= argument to ArgumentParser :

By default, the description will be line-wrapped so that it fits within the given space. To change this behavior, see the formatter_class argument.

-h, --help show this help message and exit

Most calls to the ArgumentParser constructor will use the description= keyword argument. This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments:

The %(prog)s format specifier is available to fill in the program name in your usage messages.

-h, --help show this help message and exit

The default message can be overridden with the usage= keyword argument:

-h, --help show this help message and exit

By default, ArgumentParser calculates the usage message from the arguments it contains:

-h, --help show this help message and exit

Note that the program name, whether determined from sys.argv[0] or from the prog= argument, is available to help messages using the %(prog)s format specifier.

-h, --help show this help message and exit

To change this default behavior, another value can be supplied using the prog= argument to ArgumentParser :

-h, --help show this help message and exit

-h, --help show this help message and exit

The help for this program will display myprogram.py as the program name (regardless of where the program was invoked from):

By default, ArgumentParser objects use sys.argv[0] to determine how to display the name of the program in help messages. This default is almost always desirable because it will make the help messages match how the program was invoked on the command line. For example, consider a file named myprogram.py with the following code:

The following sections describe how each of these are used.

Changed in version 3.8: In previous versions, allow_abbrev also disabled grouping of short flags such as -vv to mean -v -v .

exit_on_error - Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True )

allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True )

argument_default - The global default value for arguments (default: None )

fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None )

parents - A list of ArgumentParser objects whose arguments should also be included

epilog - Text to display after the argument help (default: none)

description - Text to display before the argument help (default: none)

usage - The string describing the program usage (default: generated from arguments added to parser)

prog - The name of the program (default: sys.argv[0] )

Create a new ArgumentParser object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:

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 parameter has 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. foo or -f, --foo .

action - The basic type of action to be taken when this argument is encountered at the command line.

nargs - The number of command-line arguments that should be consumed.

const - A constant value required by some action and nargs selections.

default - The value produced if the argument is absent from the command line.

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¶ The add_argument() method must know whether an optional argument, like -f or --foo , or a positional argument, like a list of filenames, is expected. The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name. For example, an optional argument could be created like: >>> parser . add_argument ( '-f' , '--foo' ) while a positional argument could be created like: >>> parser . add_argument ( 'bar' ) When parse_args() is called, optional arguments will be identified by the - prefix, and the remaining arguments will be assumed to be 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] bar PROG: error: the following arguments are required: bar

action¶ ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parse_args() . The action keyword argument specifies how the command-line arguments should be handled. The supplied actions are: 'store' - This just stores the argument’s value. This is the default action. 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 the const keyword argument. The 'store_const' action is most commonly used with optional 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 values True and False respectively. In addition, they create default values of False and True respectively. 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 the list. 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 by the const keyword argument to the list. (Note that the const keyword argument defaults to None .) The 'append_const' action is typically useful when multiple arguments need to store constants to the same list. For example: >>> 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. For example, 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, the default will be None unless explicitly set to 0.

'help' - This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created.

'version' - This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked: >>> import argparse >>> 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 the list. 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 or other object that implements the same interface. The BooleanOptionalAction is available in argparse and adds support for boolean actions such as --foo and --no-foo : >>> import argparse >>> parser = argparse . ArgumentParser () >>> parser . add_argument ( '--foo' , action = argparse . BooleanOptionalAction ) >>> parser . parse_args ([ '--no-foo' ]) Namespace(foo=False) The recommended way to create a custom action is to extend Action , overriding the __call__ method and optionally the __init__ and format_usage methods. An example of a custom action: >>> class FooAction ( argparse . Action ): ... def __init__ ( self , option_strings , dest , nargs = None , ** kwargs ): ... if nargs is not None : ... raise ValueError ( "nargs not allowed" ) ... super ( FooAction , self ) . __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' None Namespace(bar='1', foo=None) '2' '--foo' >>> args Namespace(bar='1', foo='2') For more details, see Action .

nargs¶ ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action. The supported values are: N (an integer). N arguments from the command line will be gathered together 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=1 produces a list of one item. This is different from the default, in which the item is produced by itself. '?' . One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples 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 and output 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 that it generally doesn’t make much sense to have more than one positional argument with nargs='*' , but multiple optional arguments with nargs='*' is possible. 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 a list. Additionally, an error message will be generated if there wasn’t at least 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 the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

const¶ The const argument of add_argument() is used to hold constant values that are not read from the command line but are required for the various ArgumentParser actions. The two most common uses of it are: When add_argument() is called with action='store_const' or action='append_const' . These actions add the const value to one of the attributes of the object returned by parse_args() . See the action description for examples.

When add_argument() is called with option strings (like -f or --foo ) and nargs='?' . This creates an optional argument that can be followed by zero or one command-line arguments. When parsing the command line, if the option string is encountered with no command-line argument following it, the value of const will be assumed instead. See the nargs description for examples. With the 'store_const' and 'append_const' actions, the const keyword argument must be given. For other actions, it defaults to None .

default¶ All optional arguments and some positional arguments may be omitted at the command line. The default keyword argument of add_argument() , whose value defaults to None , specifies what value should be used if the command-line argument is not present. For optional arguments, the default value is used when the option string was 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 default value is a string, the parser parses the value as if it were a command-line argument. In particular, the parser applies any type conversion argument, if provided, before setting the attribute on the Namespace 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 with nargs equal to ? or * , the default value is 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) Providing default=argparse.SUPPRESS causes no attribute to be added if the command-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, ArgumentParser objects read command-line arguments in as simple strings. However, quite often the command-line string should instead be interpreted as another type, like a float or int . The type keyword argument of add_argument() allows any necessary type-checking and type conversions to be performed. Common built-in types and functions can be used directly as the value of the type argument: >>> parser = argparse . ArgumentParser () >>> parser . add_argument ( 'foo' , type = int ) >>> parser . add_argument ( 'bar' , type = open ) >>> parser . parse_args ( '2 temp.txt' . split ()) Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2) See the section on the default keyword argument for information on when the type argument is applied to default arguments. To ease the use of various types of files, the argparse module provides the factory FileType which takes the mode= , bufsize= , encoding= and errors= arguments of the open() function. For example, FileType('w') can be used to create a writable file: >>> parser = argparse . ArgumentParser () >>> parser . add_argument ( 'bar' , type = argparse . FileType ( 'w' )) >>> parser . parse_args ([ 'out.txt' ]) Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>) type= can take any callable that takes a single string argument and returns the converted value: >>> def perfect_square ( string ): ... value = int ( string ) ... sqrt = math . sqrt ( value ) ... if sqrt != int ( sqrt ): ... msg = " %r is not a perfect square" % string ... raise argparse . ArgumentTypeError ( msg ) ... return value ... >>> parser = argparse . ArgumentParser ( prog = 'PROG' ) >>> parser . add_argument ( 'foo' , type = perfect_square ) >>> parser . parse_args ([ '9' ]) Namespace(foo=9) >>> parser . parse_args ([ '7' ]) usage: PROG [-h] foo PROG: error: argument foo: '7' is not a perfect square The choices keyword argument may be more convenient for type checkers that simply check against a range of values: >>> parser = argparse . ArgumentParser ( prog = 'PROG' ) >>> parser . add_argument ( 'foo' , type = int , choices = range ( 5 , 10 )) >>> parser . parse_args ([ '7' ]) Namespace(foo=7) >>> parser . parse_args ([ '11' ]) usage: PROG [-h] {5,6,7,8,9} PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9) See the choices section for more details.

choices¶ Some command-line arguments should be selected from a restricted set of values. These can be handled by passing a container object as the choices keyword argument to add_argument() . When the command line is parsed, argument values will be checked, and an error message will be displayed if 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 the choices container is checked after any type conversions have been performed, so the type of the objects in the choices container should match the type 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 the choices value, so list objects, set objects, and custom containers are all supported. This includes enum.Enum , which could be used to restrain argument’s choices; if we reuse previous rock/paper/scissors game example, this could be as follows: >>> from enum import Enum >>> class GameMove ( Enum ): ... ROCK = 'rock' ... PAPER = 'paper' ... SCISSORS = 'scissors' ... >>> parser = argparse . ArgumentParser ( prog = 'game.py' ) >>> parser . add_argument ( 'move' , type = GameMove , choices = GameMove ) >>> parser . parse_args ([ 'rock' ]) Namespace(move=<GameMove.ROCK: 'rock'>)

required¶ In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line. To make an option required, True can be specified for the required= keyword argument to add_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 as required , parse_args() will report an error if that option is not present at the command line. Note Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.

help¶ The help value is a string containing a brief description of the argument. When a user requests help (usually by using -h or --help at the command line), these help descriptions will be displayed with each argument: >>> 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 frobbled optional arguments: -h, --help show this help message and exit --foo foo the bars before frobbling The help strings can include various format specifiers to avoid repetition of things like the program name or the argument default. The available specifiers include the program name, %(prog)s and most keyword arguments to add_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 appear in the help string, you must escape it as %% . argparse supports silencing the help entry for certain options, by setting the help value to argparse.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¶ When ArgumentParser generates help messages, it needs some way to refer to each expected argument. By default, ArgumentParser objects use the dest value as the “name” of each object. By default, for positional argument actions, the dest value is used directly, and for optional argument actions, the dest value is uppercased. So, a single positional argument with dest='bar' will be referred to as bar . A single optional argument --foo that should be followed by a single command-line argument will be referred to as FOO . 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] bar positional arguments: bar optional arguments: -h, --help show this help message and exit --foo FOO An alternative name can be specified with metavar : >>> 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] XXX positional arguments: XXX optional arguments: -h, --help show this help message and exit --foo YYY Note that metavar only changes the displayed name - the name of the attribute on the parse_args() object is still determined by the dest value. Different values of nargs may cause the metavar to be used multiple times. Providing a tuple to metavar specifies a different display for each of the arguments: >>> 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¶ Most ArgumentParser actions add some value as an attribute of the object returned by parse_args() . The name of this attribute is determined by the dest keyword argument of add_argument() . For positional argument actions, dest is normally supplied as the first argument to add_argument() : >>> parser = argparse . ArgumentParser () >>> parser . add_argument ( 'bar' ) >>> parser . parse_args ([ 'XXX' ]) Namespace(bar='XXX') For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial -- string. If no long option strings were supplied, dest will be derived from the first short option string by stripping the initial - character. Any internal - characters will be converted to _ characters to make sure the string is a valid attribute name. The examples below illustrate this behavior: >>> 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')