diff -r f383acfb518d -r 09c082c8445d Doc/library/argparse.rst --- a/Doc/library/argparse.rst Sun Aug 19 12:27:38 2012 -0700 +++ b/Doc/library/argparse.rst Tue Aug 28 02:08:58 2012 -0700 @@ -28,61 +28,90 @@ Example ------- -The following code is a Python program that takes a list of integers and -produces either the sum or the max:: +.. Note! The example here is also later used in the "Beyond sys.argv" +.. section torwards the end of the doc (so if you're changing this one, +.. you may want to change the later one too!) + +The following code is the argument parser for a Python program that takes +a list of line numbers, a filename, and prints the given lines from a file:: import argparse - parser = 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)') + parser = argparse.ArgumentParser(description='Print lines from file.') + parser.add_argument('line_numbers', metavar='N', type=int, nargs='*', + help="space separated list of line numbers to print out") + parser.add_argument('-f', '--file', type=str, required=True + help="the file to print lines from") + parser.add_argument('-q', '--quiet', action="store_false", dest="verbose", + default=True, help="don't output line numbers") + args = parser.parse_args() - args = parser.parse_args() - print(args.accumulate(args.integers)) +Assuming the Python code above is saved into a file called +``printlinesfromfile.py``, it can be run at the command line +and provides useful help messages:: -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:: + $ printlinesfromfile.py -h + usage: printlinesfromfile.py [-h] [-f FILE] [-q] [N [N ...]] - $ prog.py -h - usage: prog.py [-h] [--sum] N [N ...] - - Process some integers. + Print lines from file. positional arguments: - N an integer for the accumulator + N space separated list of line numbers to print out optional arguments: - -h, --help show this help message and exit - --sum sum the integers (default: find the max) + -h, --help show this help message and exit + -f FILE, --file FILE the file to print lines out of + -q, --quiet don't output line numbers -When run with the appropriate arguments, it prints either the sum or the max of -the command-line integers:: - $ prog.py 1 2 3 4 - 4 +A sample program that could use the parser code to print specified lines from a +file might look like this:: - $ prog.py 1 2 3 4 --sum - 10 + ... + if args.line_numbers: + + with open(args.file) as f: + lines = list(f) + + if len(args.line_numbers) == 1: + lines_to_print = (lines[args.line_numbers[0]],) + else: + # pick the specified line_numbers out of the lines + lines_to_print = [line for n, line in enumerate(lines) if n in args.line_numbers] + + print('Printing lines from... {}!'.format(args.file)) + + for (i, line) in enumerate(lines_to_print): + if args.verbose: + print('Line #{}: {}'.format(args.line_numbers[i], line), end="") + else: + print(line, end="") + +When run with the right arguments, it prints the specified lines:: + + $ printlinesfromfile.py -f /usr/share/dict/words 1 11 111 543 65432 + Printing lines from... /usr/share/dict/words! + Line #1: a + Line #11: Aaronical + Line #111: abbotcy + Line #543: absolvable + Line #65432: Euglenida If invalid arguments are passed in, it will issue an error:: - $ prog.py a b c - usage: prog.py [-h] [--sum] N [N ...] - prog.py: error: argument N: invalid int value: 'a' + $ printlinesfromfile.py 1 2 bethard + usage: printlinesfromfile.py [-h] [-f FILE] [-q] [N [N ...]] + printlinesfromfile.py: error: argument N: invalid int value: 'bethard' The following sections walk you through this example. - Creating a parser ^^^^^^^^^^^^^^^^^ The first step in using the :mod:`argparse` is creating an :class:`ArgumentParser` object:: - >>> parser = argparse.ArgumentParser(description='Process some integers.') + >>> parser = argparse.ArgumentParser(description='Print lines from file.') The :class:`ArgumentParser` object will hold all the information necessary to parse the command line into Python data types. @@ -97,18 +126,17 @@ on the command line and turn them into objects. This information is stored and used when :meth:`~ArgumentParser.parse_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)') + >>> parser.add_argument('line_numbers', metavar='N', type=int, nargs='*', + help="space separated list of line numbers to print out.") + >>> parser.add_argument('-f', '--file', type=str, default="/usr/share/dict/words", + help="the file to print lines out of") + >>> parser.add_argument('-q', '--quiet', action="store_false", dest="verbose", + default=True, help="don't output line numbers") Later, calling :meth:`~ArgumentParser.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 :func:`sum` function, if ``--sum`` was specified at the command line, -or the :func:`max` function if it was not. - +three attributes: ``line_numbers``, ``file`` and ``verbose``. The ``line_numbers`` +attribute will be a list of one or more ints, the ``file`` attribute will be +a string, and the ``quiet`` attribute will be a bool. Parsing arguments ^^^^^^^^^^^^^^^^^ @@ -119,8 +147,8 @@ In most cases, this means a simple :class:`Namespace` object will be built up from attributes parsed out of the command line:: - >>> parser.parse_args(['--sum', '7', '-1', '42']) - Namespace(accumulate=, integers=[7, -1, 42]) + >>> parser.parse_args(['-f', 'somefile.txt', '7', '1', '42']) + Namespace(file='somefile.txt', line_numbers=[7, 1, 42], verbose=True) In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no arguments, and the :class:`ArgumentParser` will automatically determine the @@ -177,11 +205,12 @@ displayed between the command-line usage string and the help messages for the various arguments:: - >>> parser = argparse.ArgumentParser(description='A foo that bars') - >>> parser.print_help() - usage: argparse.py [-h] + >>> pizza_parser = argparse.ArgumentParser( + description='Make a pizza out of ingredients and toppings') + >>> pizza_parser.print_help() + usage: makepizza.py [-h] - A foo that bars + Make a pizza out of ingredients and toppings optional arguments: -h, --help show this help message and exit @@ -197,18 +226,18 @@ description of the arguments. Such text can be specified using the ``epilog=`` argument to :class:`ArgumentParser`:: - >>> 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] + >>> pizza_parser = argparse.ArgumentParser( + ... description='Make a pizza out of ingredients and toppings', + ... epilog="Remember: select a good combination to ensure maximum tastiness") + >>> pizza_parser.print_help() + usage: makepizza.py [-h] - A foo that bars + Make a pizza out of ingredients and toppings optional arguments: -h, --help show this help message and exit - And that's how you'd foo a bar + Remember: select a good combination for maximum tastiness As with the description_ argument, the ``epilog=`` text is by default line-wrapped, but this behavior can be adjusted with the formatter_class_ @@ -220,34 +249,34 @@ 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:: +``makepizza.py`` containing the following code:: import argparse - parser = argparse.ArgumentParser() - parser.add_argument('--foo', help='foo help') - args = parser.parse_args() + pizza_parser = argparse.ArgumentParser() + pizza_parser.add_argument('--size', help='what size pizza to make') + args = pizza_parser.parse_args() If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser help will be printed:: - $ python myprogram.py --help - usage: myprogram.py [-h] [--foo FOO] + $ python makepizza.py --help + usage: makepizza.py [-h] [--size SIZE] optional arguments: -h, --help show this help message and exit - --foo FOO foo help + --size SIZE what size pizza to make 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 :class:`ArgumentParser`:: - >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) - >>> parser.add_argument('--foo', help='foo help') - >>> parser.print_help() - usage: PROG [--foo FOO] + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza', add_help=False) + >>> pizza_parser.add_argument('--size', help='what size pizza to make') + >>> pizza_parser.print_help() + usage: makepizza [--size SIZE] optional arguments: - --foo FOO foo help + --size SIZE what size pizza to make The help option is typically ``-h/--help``. The exception to this is if the ``prefix_chars=`` is specified and does not include ``-``, in @@ -266,20 +295,21 @@ prefix_chars ^^^^^^^^^^^^ -Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``. +Most command-line options will use ``-`` as the prefix, e.g. ``-s/--size``. 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 +like ``+s`` or ``/size``, may specify them using the ``prefix_chars=`` argument to 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') + >>> pizza_parser = argparse.ArgumentParser(prefix_chars='-+') + >>> pizza_parser.add_argument('+s') + >>> pizza_parser.add_argument('++cheese') + >>> pizza_parser.add_argument('--sauce') + >>> pizza_parser.parse_args('+s large ++cheese extra --sauce pesto'.split()) + Namespace(cheese='extra', s='large', sauce='pesto') The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of -characters that does not include ``-`` will cause ``-f/--foo`` options to be +characters that does not include ``-`` will cause ``-s/--size`` options to be disallowed. @@ -294,17 +324,17 @@ arguments they contain. For example:: >>> with open('args.txt', 'w') as fp: - ... fp.write('-f\nbar') - >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@') - >>> parser.add_argument('-f') - >>> parser.parse_args(['-f', 'foo', '@args.txt']) - Namespace(f='bar') + ... fp.write('-s\nextralarge') + >>> pizza_parser = argparse.ArgumentParser(fromfile_prefix_chars='@') + >>> pizza_parser.add_argument('-s') + >>> pizza_parser.parse_args(['-s', 'size', '@args.txt']) + Namespace(s='extralarge') Arguments read from a file must by default be one per line (but see also :meth:`~ArgumentParser.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']``. +line. So in the example above, the expression ``['-s', 'size', '@args.txt']`` +is considered equivalent to the expression ``['-s', 'size', '-s', 'extralarge']``. The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that arguments will never be treated as file references. @@ -322,12 +352,12 @@ to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args` calls, we supply ``argument_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([]) + >>> pizza_parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) + >>> pizza_parser.add_argument('--size') + >>> pizza_parser.add_argument('crust', nargs='?') + >>> pizza_parser.parse_args(['--size', 'large', 'thin']) + Namespace(crust='thin', size='large') + >>> pizza_parser.parse_args([]) Namespace() @@ -339,20 +369,23 @@ shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser` can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser` objects, collects all the positional and optional actions from them, and adds -these actions to the :class:`ArgumentParser` object being constructed:: +these actions to the :class:`ArgumentParser` object being constructed. - >>> parent_parser = argparse.ArgumentParser(add_help=False) - >>> parent_parser.add_argument('--parent', type=int) +In the example below, since pizzas usually all have sort of sauce base, it +make sense to make it a parent argument:: - >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser]) - >>> foo_parser.add_argument('foo') - >>> foo_parser.parse_args(['--parent', '2', 'XXX']) - Namespace(foo='XXX', parent=2) + >>> pizza_parser = argparse.ArgumentParser(add_help=False) + >>> pizza_parser.add_argument('--sauce', type=str) - >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser]) - >>> bar_parser.add_argument('--bar') - >>> bar_parser.parse_args(['--bar', 'YYY']) - Namespace(bar='YYY', parent=None) + >>> meat_pizza_parser = argparse.ArgumentParser(parents=[pizza_parser]) + >>> meat_pizza_parser.add_argument('crust') + >>> meat_pizza_parser.parse_args(['--sauce', 'barbecue', 'stuffed']) + Namespace(sauce='barbecue', crust='stuffed') + + >>> strange_pizza_parser = argparse.ArgumentParser(parents=[pizza_parser]) + >>> strange_pizza_parser.add_argument('--crust') + >>> strange_pizza_parser.parse_args(['--crust', 'stuffed']) + Namespace(crust='stuffed', sauce=None) Note that most parent parsers will specify ``add_help=False``. Otherwise, the :class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent @@ -433,40 +466,43 @@ :class:`ArgumentDefaultsHelpFormatter` automatically adds information about default values to each of the argument help messages:: - >>> parser = argparse.ArgumentParser( - ... prog='PROG', + >>> pizza_parser = argparse.ArgumentParser( + ... prog='makepizza', ... 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 [bar ...]] + >>> pizza_parser.add_argument('--sauce', type=str, default='tomato', + ... help='the sauce to use') + >>> pizza_parser.add_argument('toppings', nargs='*', metavar='topping', + default=['beef' ,'garlic'], + help='the toppings to put on') + >>> pizza_parser.print_help() + usage: makepizza [-h] [--sauce SAUCE] [topping [topping ...]] positional arguments: - bar BAR! (default: [1, 2, 3]) + topping the toppings to put on (default: ['beef', 'garlic']) optional arguments: - -h, --help show this help message and exit - --foo FOO FOO! (default: 42) + -h, --help show this help message and exit + --sauce SAUCE the sauce to use (default: tomato) :class:`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):: - >>> parser = argparse.ArgumentParser( - ... prog='PROG', + >>> pizza_parser = argparse.ArgumentParser( + ... prog='makepizza', ... formatter_class=argparse.MetavarTypeHelpFormatter) - >>> parser.add_argument('--foo', type=int) - >>> parser.add_argument('bar', type=float) - >>> parser.print_help() - usage: PROG [-h] [--foo int] float + >>> pizza_parser.add_argument('--sauce', type=str) + >>> pizza_parser.add_argument('slices', type=int, + ... help="how many slices the pizza will be cut up into") + >>> pizza_parser.print_help() + usage: makepizza [-h] [--sauce str] int positional arguments: - float + int how many slices the pizza will be cut up into optional arguments: - -h, --help show this help message and exit - --foo int - + -h, --help show this help message and exit + --sauce str conflict_handler ^^^^^^^^^^^^^^^^ @@ -476,32 +512,33 @@ attempt is made to create an argument with an option string that is already in use:: - >>> parser = argparse.ArgumentParser(prog='PROG') - >>> parser.add_argument('-f', '--foo', help='old foo help') - >>> parser.add_argument('--foo', help='new foo help') + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('-s', '--sauce', help='the first sauce to use') + >>> pizza_parser.add_argument('--sauce', help='pizzas with two sauces are weird') Traceback (most recent call last): .. - ArgumentError: argument --foo: conflicting option string(s): --foo + ArgumentError: argument --sauce: conflicting option string: --sauce 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 :class:`ArgumentParser`:: - >>> 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] + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza', + ... conflict_handler='resolve') + >>> pizza_parser.add_argument('-s', '--sauce', help='the first sauce to use') + >>> pizza_parser.add_argument('--sauce', help='a second sauce to use') + >>> pizza_parser.print_help() + usage: makepizza [-h] [-s SAUCE] [--sauce SAUCE] optional arguments: - -h, --help show this help message and exit - -f FOO old foo help - --foo FOO new foo help + -h, --help show this help message and exit + -s SAUCE the old sauce to use + --sauce SAUCE a second sauce to use Note that :class:`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 +option strings are overridden. So, in the example above, the old ``-s/--sauce`` +action is retained as the ``-s`` action, because only the ``--sauce`` option string was overridden. @@ -516,32 +553,30 @@ import argparse parser = argparse.ArgumentParser() - parser.add_argument('--foo', help='foo help') args = parser.parse_args() The help for this program will display ``myprogram.py`` as the program name (regardless of where the program was invoked from):: $ python myprogram.py --help - usage: myprogram.py [-h] [--foo FOO] + usage: myprogram.py [-h] optional arguments: - -h, --help show this help message and exit - --foo FOO foo help + -h, --help show this help message and exit $ cd .. $ python subdir\myprogram.py --help - usage: myprogram.py [-h] [--foo FOO] + usage: myprogram.py [-h] optional arguments: - -h, --help show this help message and exit - --foo FOO foo help + -h, --help show this help message and exit + To change this default behavior, another value can be supplied using the ``prog=`` argument to :class:`ArgumentParser`:: - >>> parser = argparse.ArgumentParser(prog='myprogram') + >>> parser = argparse.ArgumentParser(prog='zip-a-dee-doo-dah') >>> parser.print_help() - usage: myprogram [-h] + usage: zip-a-dee-doo-dah [-h] optional arguments: -h, --help show this help message and exit @@ -552,15 +587,14 @@ :: - >>> parser = argparse.ArgumentParser(prog='myprogram') - >>> parser.add_argument('--foo', help='foo of the %(prog)s program') + >>> parser = argparse.ArgumentParser(prog='zip-a-dee-doo-dah') + >>> parser.add_argument('--spam', help='How noisy %(prog)s will be :P') >>> parser.print_help() - usage: myprogram [-h] [--foo FOO] + usage: zip-a-dee-doo-dah [-h] [--spam SPAM] optional arguments: - -h, --help show this help message and exit - --foo FOO foo of the myprogram program - + -h, --help show this help message and exit + --spam SPAM How noisy zip-a-dee-doo-dah will be :P usage ^^^^^ @@ -568,33 +602,34 @@ By default, :class:`ArgumentParser` calculates the usage message from the arguments 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 ...] + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('--sauce', nargs='?') + >>> pizza_parser.add_argument('toppings', metavar='topping', nargs='+') + >>> pizza_parser.print_help() + usage: makepizza [-h] [--sauce [SAUCE]] topping [topping ...] positional arguments: - bar bar help + topping optional arguments: - -h, --help show this help message and exit - --foo [FOO] foo help + -h, --help show this help message and exit + --sauce [SAUCE] The default message can be overridden with the ``usage=`` 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] + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza', + ... usage='%(prog)s [list of yummy toppings...]') + >>> pizza_parser.add_argument('--sauce', nargs='?') + >>> pizza_parser.add_argument('toppings', metavar='topping', nargs='+') + >>> pizza_parser.print_help( + usage: makepizza [list of yummy toppings...] positional arguments: - bar bar help + topping optional arguments: - -h, --help show this help message and exit - --foo [FOO] foo help + -h, --help show this help message and exit + --sauce [SAUCE] The ``%(prog)s`` format specifier is available to fill in the program name in your usage messages. @@ -610,8 +645,8 @@ 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``. + * `name or flags`_ - Either a name or a list of option strings, e.g. ``sauce`` + or ``-s, --sauce``. * action_ - The basic type of action to be taken when this argument is encountered at the command line. @@ -644,33 +679,32 @@ ^^^^^^^^^^^^^ The :meth:`~ArgumentParser.add_argument` method must know whether an optional -argument, like ``-f`` or ``--foo``, or a positional argument, like a list of +argument, like ``-s`` or ``--size``, or a positional argument, like a list of filenames, is expected. The first arguments passed to :meth:`~ArgumentParser.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') + >>> pizza_parser.add_argument('-s', '--size') while a positional argument could be created like:: - >>> parser.add_argument('bar') + >>> pizza_parser.add_argument('crust') When :meth:`~ArgumentParser.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: too few arguments - + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('-s', '--size') + >>> pizza_parser.add_argument('crust') + >>> pizza_parser.parse_args(['deepdish']) + Namespace(crust='deepdish', size=None) + >>> pizza_parser.parse_args(['deepdish', '--size', 'medium']) + Namespace(crust=='deepdish', size='medium') + >>> pizza_parser.parse_args(['--size', 'medium']) + usage: makepizza [-h] [-s SIZE] crust + makepizza: error: the following arguments are required: crust action ^^^^^^ @@ -685,9 +719,9 @@ action. For example:: >>> parser = argparse.ArgumentParser() - >>> parser.add_argument('--foo') - >>> parser.parse_args('--foo 1'.split()) - Namespace(foo='1') + >>> parser.add_argument('--age') + >>> parser.parse_args('--age 26'.split()) + Namespace(age='26') * ``'store_const'`` - This stores the value specified by the const_ keyword argument. (Note that the const_ keyword argument defaults to the rather @@ -695,28 +729,28 @@ 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'.split()) - Namespace(foo=42) + >>> parser.add_argument('--age', action='store_const', const=42) + >>> parser.parse_args('--age'.split()) + Namespace(age=42) * ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and ``False`` respectively. These are special cases of ``'store_const'``. For example:: >>> parser = argparse.ArgumentParser() - >>> parser.add_argument('--foo', action='store_true') - >>> parser.add_argument('--bar', action='store_false') - >>> parser.parse_args('--foo --bar'.split()) - Namespace(bar=False, foo=True) + >>> parser.add_argument('--smelly', action='store_true') + >>> parser.add_argument('--intelligent', action='store_false') + >>> parser.parse_args('--smelly --intelligent'.split()) + Namespace(intelligent=False, smelly=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']) + >>> parser.add_argument('--trait', action='append') + >>> parser.parse_args('--trait smelly --trait intelligent'.split()) + Namespace(trait=['smelly', 'intelligent']) * ``'append_const'`` - This stores a list, and appends the value specified by the const_ keyword argument to the list. (Note that the const_ keyword @@ -774,20 +808,19 @@ An example of a custom action:: - >>> class FooAction(argparse.Action): + >>> class PrintArgumentAction(argparse.Action): ... 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' + >>> parser.add_argument('--pineapples', action=PrintArgumentAction) + >>> parser.add_argument('mangos', action=PrintArgumentAction) + >>> args = parser.parse_args('1 --pineapples 2'.split()) + Namespace(mangos=None, pineapples=None) '1' None + Namespace(mangos='1', pineapples=None) '2' '--pineapples' >>> args - Namespace(bar='1', foo='2') - + Namespace(mangos='1', pineapples='2') nargs ^^^^^ @@ -800,11 +833,11 @@ * ``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']) + >>> parser = argparse.ArgumentParser(description="Parse ISO 6709 coordinate!") + >>> parser.add_argument('--coordinates', nargs=2) + >>> parser.add_argument('--name', nargs=1) + >>> parser.parse_args(['--name=San Francisco', '--coordinates', '37.7', '-122.4']) + Namespace(coordinates=['37.7', '-122.4'], name=['San Francisco']) Note that ``nargs=1`` produces a list of one item. This is different from the default, in which the item is produced by itself. @@ -817,14 +850,14 @@ 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'.split()) - Namespace(bar='XX', foo='YY') - >>> parser.parse_args('XX --foo'.split()) - Namespace(bar='XX', foo='c') + >>> parser.add_argument('--language', nargs='?', const='Python', default='Python3') + >>> parser.add_argument('adjective', nargs='?', default='Awesome!') + >>> parser.parse_args('painful --language COBOL'.split()) + Namespace(adjective='painful', language='COBOL') + >>> parser.parse_args('Great! --language'.split()) + Namespace(adjective='Great!', language='Python') >>> parser.parse_args(''.split()) - Namespace(bar='d', foo='d') + Namespace(adjective='Awesome!', language='Python3') One of the more common uses of ``nargs='?'`` is to allow optional input and output files:: @@ -846,35 +879,35 @@ 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']) + >>> parser = argparse.ArgumentParser(prog="the-lottery-is-fun") + >>> parser.add_argument('--lucky', nargs='*') + >>> parser.add_argument('--unlucky', nargs='*') + >>> parser.add_argument('gamblingdays', nargs='*') + >>> parser.parse_args('14 22 3 31 --lucky 1 7 11 --unlucky 13'.split()) + Namespace(gamblingdays=['14', '22', '3', '31'], lucky=['1', '7', '11'], unlucky=['13']) * ``'+'``. 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'.split()) - Namespace(foo=['a', 'b']) + >>> parser = argparse.ArgumentParser(prog="the-lottery-is-fun") + >>> parser.add_argument('gamblingdays', nargs='+') + >>> parser.parse_args('14 22 3 31'.split()) + Namespace(gamblingdays=['14', '22', '3', '31']) >>> parser.parse_args(''.split()) - usage: PROG [-h] foo [foo ...] - PROG: error: too few arguments + usage: the-lottery-is-fun [-h] gamblingdays [gamblingdays ...] + the-lottery-is-fun: error: the following arguments are required: gamblingdays * ``argparse.REMAINDER``. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities:: - >>> parser = argparse.ArgumentParser(prog='PROG') - >>> parser.add_argument('--foo') - >>> parser.add_argument('command') - >>> parser.add_argument('args', nargs=argparse.REMAINDER) - >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())) - Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B') + >>> parser = argparse.ArgumentParser(prog='the-lottery-is-fun') + >>> parser.add_argument('--name') + >>> parser.add_argument('wager') + >>> parser.add_argument('numbers', nargs=argparse.REMAINDER) + >>> print(parser.parse_args('--name PyLotto 4.99 --numbers 2 4 6 8 50'.split())) + Namespace(name='PyLotto', numbers=['--numbers', '2', '4', '6', '8', '50'], wager='4.99') 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 @@ -913,33 +946,33 @@ 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'.split()) - Namespace(foo='2') - >>> parser.parse_args(''.split()) - Namespace(foo=42) + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--sauce', default='tomato') + >>> pizza_parser.parse_args('--sauce pesto'.split()) + Namespace(sauce='pesto') + >>> pizza_parser.parse_args(''.split()) + Namespace(sauce=tomato) 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'.split()) - Namespace(foo='a') - >>> parser.parse_args(''.split()) - Namespace(foo=42) + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('toppings', nargs='*', default=['anchovies']) + >>> pizza_parser.parse_args('sausage ants pineapple'.split()) + Namespace(toppings=['sausage', 'ants', 'pineapple']) + >>> pizza_parser.parse_args([]) + Namespace(toppings=['anchovies']) 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([]) + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--sauce', default=argparse.SUPPRESS) + >>> pizza_parser.parse_args(['--sauce', 'pesto']) + Namespace(sauce='pesto') + >>> pizza_parser.parse_args([]) Namespace() - >>> parser.parse_args(['--foo', '1']) - Namespace(foo='1') type @@ -952,21 +985,21 @@ 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) + >>> get_lines_parser = argparse.ArgumentParser() + >>> get_lines_parser.add_argument('lines', type=int) + >>> get_lines_parser.add_argument('somefile', type=open) + >>> get_lines_parser.parse_args('2 temp.txt'.split()) + Namespace(lines=2, somefile=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>) To ease the use of various types of files, the argparse module provides the factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the :func:`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'>) + >>> get_lines_parser = argparse.ArgumentParser() + >>> get_lines_parser.add_argument('outfile', type=argparse.FileType('w')) + >>> get_lines_parser.parse_args(['out.txt']) + Namespace(outfile=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>) ``type=`` can take any callable that takes a single string argument and returns the converted value:: @@ -979,24 +1012,24 @@ ... raise argparse.ArgumentTypeError(msg) ... return value ... - >>> parser = argparse.ArgumentParser(prog='PROG') - >>> parser.add_argument('foo', type=perfect_square) + >>> parser = argparse.ArgumentParser(prog='isperfectsquare') + >>> parser.add_argument('number', type=perfect_square) >>> parser.parse_args('9'.split()) - Namespace(foo=9) + Namespace(number=9) >>> parser.parse_args('7'.split()) - usage: PROG [-h] foo - PROG: error: argument foo: '7' is not a perfect square + usage: isperfectsquare [-h] number + isperfectsquare: error: argument number: '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 = argparse.ArgumentParser(prog='numberchecker') + >>> parser.add_argument('number', type=int, choices=range(5, 10)) >>> parser.parse_args('7'.split()) - Namespace(foo=7) - >>> parser.parse_args('11'.split()) - usage: PROG [-h] {5,6,7,8,9} - PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9) + Namespace(number=7) + >>> parser.parse_args('0'.split()) + usage: numberchecker [-h] {5,6,7,8,9} + numberchecker: error: argument number: invalid choice: 0 (choose from 5, 6, 7, 8, 9) See the choices_ section for more details. @@ -1010,25 +1043,26 @@ 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='PROG') - >>> parser.add_argument('foo', choices='abc') - >>> parser.parse_args('c'.split()) - Namespace(foo='c') - >>> parser.parse_args('X'.split()) - usage: PROG [-h] {a,b,c} - PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c') + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('crust', + ... choices=['thin', 'deepdish', 'stuffed', 'regular']) + >>> pizza_parser.parse_args(['thin']) + Namespace(crust='thin') + >>> pizza_parser.parse_args(['chocolate']) + usage: makepizza [-h] {thin,deepdish,stuffed,regular} + makepizza: error: argument crust: invalid choice: 'chocolate' (choose from 'thin', 'deepdish', 'stuffed', 'regular') 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='PROG') - >>> parser.add_argument('foo', type=complex, choices=[1, 1j]) + >>> parser.add_argument('complex_number', type=complex, choices=[1, 1j]) >>> parser.parse_args('1j'.split()) - Namespace(foo=1j) + Namespace(complex_number=1j) >>> parser.parse_args('-- -4'.split()) usage: PROG [-h] {1,1j} - PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j) + PROG: error: argument complex_number: invalid choice: (-4+0j) (choose from 1, 1j) Any object that supports the ``in`` operator can be passed as the ``choices`` value, so :class:`dict` objects, :class:`set` objects, custom containers, @@ -1043,13 +1077,13 @@ To make an option *required*, ``True`` can be specified for the ``required=`` keyword argument to :meth:`~ArgumentParser.add_argument`:: - >>> parser = argparse.ArgumentParser() - >>> parser.add_argument('--foo', required=True) - >>> parser.parse_args(['--foo', 'BAR']) - Namespace(foo='BAR') + >>> pizza_parser = argparse.ArgumentParser(prog="pizzaparser") + >>> pizza_parser.add_argument('--sauce', required=True) + >>> pizza_parser.parse_args(['--sauce', 'barbeque']) + Namespace(sauce='barbeque') >>> parser.parse_args([]) - usage: argparse.py [-h] [--foo FOO] - argparse.py: error: option --foo is required + usage: pizzaparser [-h] --sauce SAUCE + makepizza.py: error: option --sauce is required As the example shows, if an option is marked as ``required``, :meth:`~ArgumentParser.parse_args` will report an error if that option is not @@ -1069,37 +1103,36 @@ 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'.split()) - usage: frobble [-h] [--foo] bar [bar ...] + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('--sauce', help='the sauce to use on the pizza') + >>> pizza_parser.add_argument('topping', nargs='+', + ... help='the toppings to put on the pizza') + >>> pizza_parser.parse_args('-h'.split()) + usage: makepizza [-h] [--sauce SAUCE] topping [topping ...] positional arguments: - bar one of the bars to be frobbled + topping the toppings to put on the pizza optional arguments: - -h, --help show this help message and exit - --foo foo the bars before frobbling + -h, --help show this help message and exit + --sauce SAUCE the sauce to use on the pizza 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 :meth:`~ArgumentParser.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] + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('slices', nargs='?', type=int, default=8, + ... help='number of slices %(prog)s should cut (default: %(default)s)') + >>> pizza_parser.print_help() + usage: makepizza [-h] [slices] positional arguments: - bar the bar to frobble (default: 42) + slices number of slices makepizza should cut up (default: 10) optional arguments: - -h, --help show this help message and exit + -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 ``%%``. @@ -1107,10 +1140,10 @@ :mod:`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] + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('--sauce', help=argparse.SUPPRESS) + >>> pizza_parser.print_help() + usage: makepizza [-h] optional arguments: -h, --help show this help message and exit @@ -1119,46 +1152,47 @@ metavar ^^^^^^^ -When :class:`ArgumentParser` generates help messages, it need some way to refer +When :class:`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:: +``dest='crust'`` will be referred to as ``crust``. A single +optional argument ``--sauce`` that should be followed by a single command-line +argument will be referred to as ``SAUCE``. 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 + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--sauce') + >>> pizza_parser.add_argument('crust') + >>> pizza_parser.parse_args('stuffed --sauce tomato'.split()) + Namespace(crust='stuffed', sauce='tomato') + >>> pizza_parser.print_help() + usage: [-h] [--sauce SAUCE] crust positional arguments: - bar + crust optional arguments: - -h, --help show this help message and exit - --foo FOO + -h, --help show this help message and exit + --sauce SAUCE 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 + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--sauce', metavar="S") + >>> pizza_parser.add_argument('crust', metavar="WHATCRUST") + >>> pizza_parser.parse_args('stuffed --sauce tomato'.split()) + Namespace(crust='stuffed', sauce='tomato') + >>> pizza_parser.print_help() + usage: [-h] [--sauce S] WHATCRUST positional arguments: - XXX + WHATCRUST optional arguments: - -h, --help show this help message and exit - --foo YYY + -h, --help show this help message and exit + --sauce S + Note that ``metavar`` only changes the *displayed* name - the name of the attribute on the :meth:`~ArgumentParser.parse_args` object is still determined @@ -1168,16 +1202,18 @@ 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 = argparse.ArgumentParser(description="Parse ISO 6709 coordinate!") + >>> parser.add_argument('--coordinates', nargs=2, metavar=('longitude', 'latitude')) + >>> parser.add_argument('--name', nargs=1, help="name of location") >>> parser.print_help() - usage: PROG [-h] [-x X X] [--foo bar baz] + usage: [-h] [--coordinates longitude latitude] [--name NAME] + + Parse ISO 6709 coordinate! optional arguments: - -h, --help show this help message and exit - -x X X - --foo bar baz + -h, --help show this help message and exit + --coordinates longitude latitude + --name NAME name of location dest @@ -1190,10 +1226,10 @@ ``dest`` is normally supplied as the first argument to :meth:`~ArgumentParser.add_argument`:: - >>> parser = argparse.ArgumentParser() - >>> parser.add_argument('bar') - >>> parser.parse_args('XXX'.split()) - Namespace(bar='XXX') + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('size') + >>> pizza_parser.parse_args('large'.split()) + Namespace(size='large') For optional argument actions, the value of ``dest`` is normally inferred from the option strings. :class:`ArgumentParser` generates the value of ``dest`` by @@ -1204,20 +1240,20 @@ 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') + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('-s', '--pizza-size', '--size') + >>> pizza_parser.add_argument('-x', '-y') + >>> pizza_parser.parse_args('-s 1 -x 2'.split()) + Namespace(pizza_size='1', x='2') + >>> pizza_parser.parse_args('--size extralarge -y 2'.split()) + Namespace(pizza_size='extralarge', 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') + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--size', dest='pizzasize') + >>> pizza_parser.parse_args('--size veryverysmall'.split()) + Namespace(pizzasize='veryverysmall') The parse_args() method @@ -1243,36 +1279,36 @@ specifying the value of an option (if it takes one). In the simplest case, the option 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'.split()) - Namespace(foo=None, x='X') - >>> parser.parse_args('--foo FOO'.split()) - Namespace(foo='FOO', x=None) + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('-n') + >>> pizza_parser.add_argument('--size') + >>> pizza_parser.parse_args('-n N'.split()) + Namespace(n='N', size=None) + >>> pizza_parser.parse_args('--size medium'.split()) + Namespace(n=None, size='medium') For long options (options with names longer than a single character), the option and value can also be passed as a single command-line argument, using ``=`` to separate them:: - >>> parser.parse_args('--foo=FOO'.split()) - Namespace(foo='FOO', x=None) + >>> pizza_parser.parse_args('--size=medium'.split()) + Namespace(n=None, size='medium') For short options (options only one character long), the option and its value can be concatenated:: - >>> parser.parse_args('-xX'.split()) - Namespace(foo=None, x='X') + >>> pizza_parser.parse_args('-nN'.split()) + Namespace(n='N', size=None) 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'.split()) - Namespace(x=True, y=True, z='Z') + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('-p', action='store_true', help='Add pepperoni') + >>> pizza_parser.add_argument('-s', action='store_true', help='Add sausage') + >>> pizza_parser.add_argument('-z') + >>> pizza_parser.parse_args('-pszZ'.split()) + Namespace(p=True, s=True, z='Z') Invalid arguments @@ -1283,24 +1319,24 @@ 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='?') + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> pizza_parser.add_argument('--slices', type=int) + >>> pizza_parser.add_argument('crust', nargs='?') >>> # invalid type - >>> parser.parse_args(['--foo', 'spam']) - usage: PROG [-h] [--foo FOO] [bar] - PROG: error: argument --foo: invalid int value: 'spam' + >>> pizza_parser.parse_args(['--slices', 'spam']) + usage: makepizza [-h] [--slices SLICES] [crust] + makepizza: error: argument --slices: invalid int value: 'spam' >>> # invalid option - >>> parser.parse_args(['--bar']) - usage: PROG [-h] [--foo FOO] [bar] - PROG: error: no such option: --bar + >>> pizza_parser.parse_args(['--crust']) + usage: makepizza [-h] [--slices SLICES] [crust] + makepizza: error: unrecognized arguments: --crust >>> # wrong number of arguments - >>> parser.parse_args(['spam', 'badger']) - usage: PROG [-h] [--foo FOO] [bar] - PROG: error: extra arguments found: badger + >>> pizza_parser.parse_args(['deepdish', 'vegetable']) + usage: makepizza [-h] [--slices SLICES] [crust] + makepizza: error: unrecognized arguments: vegetable Arguments containing ``-`` @@ -1327,7 +1363,7 @@ Namespace(foo='-5', x='-1') >>> parser = argparse.ArgumentParser(prog='PROG') - >>> parser.add_argument('-1', dest='one') + >>> parser.add_argument('-1', dest='one', help="Here's a negative number option") >>> parser.add_argument('foo', nargs='?') >>> # negative number options present, so -1 is an option @@ -1376,22 +1412,23 @@ Beyond ``sys.argv`` ^^^^^^^^^^^^^^^^^^^ -Sometimes it may be useful to have an ArgumentParser parse arguments other than those -of :data:`sys.argv`. This can be accomplished by passing a list of strings to -:meth:`~ArgumentParser.parse_args`. This is useful for testing at the -interactive prompt:: +.. Note! The example here is the same one used in +.. the very first "Example" section at the beginning of the doc - >>> 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=, integers=[1, 2, 3, 4]) - >>> parser.parse_args('1 2 3 4 --sum'.split()) - Namespace(accumulate=, integers=[1, 2, 3, 4]) +Sometimes it may be useful to have an ArgumentParser parse arguments other than +those of :data:`sys.argv`. This can be accomplished by passing a list of +strings to :meth:`~ArgumentParser.parse_args`. This is useful for testing at +the interactive prompt:: + + >>> parser = argparse.ArgumentParser(description='Print lines from file.') + >>> parser.add_argument('line_numbers', metavar='N', type=int, nargs='*', + help="space separated list of line numbers to print out.") + >>> parser.add_argument('-f', '--file', type=str, + help="the file to print lines out of") + >>> parser.parse_args(['1', '12', '123', '1234']) + Namespace(file=None, line_numbers=[1, 12, 123, 1234]) + >>> parser.parse_args('1 12 123 1234 --file /path/to/file'.split()) + Namespace(file='/path/to/file', line_numbers=[1, 12, 123, 1234]) The Namespace object @@ -1406,25 +1443,25 @@ readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, :func:`vars`:: - >>> parser = argparse.ArgumentParser() - >>> parser.add_argument('--foo') - >>> args = parser.parse_args(['--foo', 'BAR']) + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--sauce') + >>> args = pizza_parser.parse_args(['--sauce', 'tomato']) >>> vars(args) - {'foo': 'BAR'} + {'sauce': 'tomato'} It may also be useful to have an :class:`ArgumentParser` assign attributes to an already existing object, rather than a new :class:`Namespace` object. This can be achieved by specifying the ``namespace=`` keyword argument:: - >>> class C: + >>> class Pizza: ... pass ... - >>> c = C() - >>> parser = argparse.ArgumentParser() - >>> parser.add_argument('--foo') - >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c) - >>> c.foo - 'BAR' + >>> pizza = Pizza() + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--sauce') + >>> pizza_parser.parse_args(args=['--sauce', 'tomato'], namespace=pizza) + >>> pizza.sauce + 'tomato' Other utilities @@ -1436,8 +1473,8 @@ .. method:: ArgumentParser.add_subparsers() Many programs split up their functionality into a number of sub-commands, - for example, the ``svn`` program can invoke sub-commands like ``svn - checkout``, ``svn update``, and ``svn commit``. Splitting up functionality + for example, the ``hg`` program can invoke sub-commands like ``hg + checkout``, ``hg update``, and ``hg commit``. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. :class:`ArgumentParser` supports the creation of such sub-commands with the @@ -1450,30 +1487,32 @@ Some example usage:: >>> # create the top-level parser - >>> parser = argparse.ArgumentParser(prog='PROG') - >>> parser.add_argument('--foo', action='store_true', help='foo help') + >>> parser = argparse.ArgumentParser(prog='makepizza') + >>> parser.add_argument('--yummy', action='store_true', + ... help='Whether or not pizzas created should be appetizing') >>> 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 "stats" command + >>> parser_stats = subparsers.add_parser('stats', + ... help='Show history of pizzas made') + >>> parser_stats.add_argument('n', type=int, help='The number of pizzas to show') >>> - >>> # 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') + >>> # create the parser for the "make" command + >>> parser_make = subparsers.add_parser('make', help='Make a pizza') + >>> parser_make.add_argument('--sauce', choices=["tomato", "bbq", "pesto"]) >>> >>> # 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) + >>> parser.parse_args(['stats', '10']) + Namespace(n=10, yummy=False) + >>> parser.parse_args(['--yummy', 'make', '--sauce', 'bbq']) + Namespace(sauce='bbq', yummy=True) Note that the object returned by :meth:`parse_args` will only contain attributes for the main parser and the subparser that was selected by the command line (and not any other subparsers). So in the example above, when - the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are - present, and when the ``b`` command is specified, only the ``foo`` and - ``baz`` attributes are present. + the ``stats`` command is specified, only the ``n`` and ``yummy`` attributes are + present, and when the ``make`` command is specified, only the ``sauce`` and + ``yummy`` attributes are present. Similarly, when a help message is requested from a subparser, only the help for that particular parser will be printed. The help message will not @@ -1484,64 +1523,68 @@ :: >>> parser.parse_args(['--help']) - usage: PROG [-h] [--foo] {a,b} ... + usage: makepizza [-h] [--yummy] {stats,make} ... positional arguments: - {a,b} sub-command help - a a help - b b help + {stats,make} sub-command help + stats Show history of pizzas made + make Make a pizza optional arguments: - -h, --help show this help message and exit - --foo foo help + -h, --help show this help message and exit + --yummy Whether or not pizzas created should be appetizing - >>> parser.parse_args(['a', '--help']) - usage: PROG a [-h] bar + + >>> parser.parse_args(['stats', '--help']) + usage: makepizza stats [-h] n positional arguments: - bar bar help + n The number of pizzas to show optional arguments: - -h, --help show this help message and exit + -h, --help show this help message an - >>> parser.parse_args(['b', '--help']) - usage: PROG b [-h] [--baz {X,Y,Z}] + + >>> parser.parse_args(['make', '--help']) + usage: makepizza make [-h] [--sauce {tomato,bbq,pesto}] optional arguments: - -h, --help show this help message and exit - --baz {X,Y,Z} baz help + -h, --help show this help message and exit + --sauce {tomato,bbq,pesto} The :meth:`add_subparsers` method also supports ``title`` and ``description`` keyword arguments. When either is present, the subparser's commands will appear in their own group in the help output. For example:: - >>> parser = argparse.ArgumentParser() + >>> parser = argparse.ArgumentParser(prog='makepizza') >>> subparsers = parser.add_subparsers(title='subcommands', ... description='valid subcommands', - ... help='additional help') - >>> subparsers.add_parser('foo') - >>> subparsers.add_parser('bar') + ... help='--what they do--') + >>> subparsers.add_parser('stats', help='Show history of made pizzas') + >>> subparsers.add_parser('make', help='Make a pizza') >>> parser.parse_args(['-h']) - usage: [-h] {foo,bar} ... + usage: makepizza [-h] {stats,make} ... optional arguments: - -h, --help show this help message and exit + -h, --help show this help message and exit subcommands: valid subcommands - {foo,bar} additional help + {stats,make} --what they do-- + stats Show history of made pizzas + make Make a pizza Furthermore, ``add_parser`` supports an additional ``aliases`` argument, which allows multiple strings to refer to the same subparser. This example, - like ``svn``, aliases ``co`` as a shorthand for ``checkout``:: + like ``hg``, aliases ``ci`` as a shorthand for ``commit``:: >>> 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') + >>> commit = subparsers.add_parser('commit', aliases=['ci']) + >>> commit.add_argument('file') + >>> parser.parse_args(['ci', 'somefile.py']) + Namespace(file='somefile.py') One particularly effective way of handling sub-commands is to combine the use of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so @@ -1549,34 +1592,34 @@ example:: >>> # sub-command functions - >>> def foo(args): - ... print(args.x * args.y) + >>> def multiply(args): + ... print(args.x * args.y) ... - >>> def bar(args): - ... print('((%s))' % args.z) + >>> def parenthesize(args): + ... print('((%s))' % args.some_string) ... >>> # 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 "multiply" command + >>> parser_multiply = subparsers.add_parser('multiply') + >>> parser_multiply.add_argument('-x', type=int, default=1) + >>> parser_multiply.add_argument('y', type=float) + >>> parser_multiply.set_defaults(func=multiply) >>> - >>> # create the parser for the "bar" command - >>> parser_bar = subparsers.add_parser('bar') - >>> parser_bar.add_argument('z') - >>> parser_bar.set_defaults(func=bar) + >>> # create the parser for the "parenthesize" command + >>> parser_parenthesize = subparsers.add_parser('parenthesize') + >>> parser_parenthesize.add_argument('some_string') + >>> parser_parenthesize.set_defaults(func=parenthesize) >>> >>> # parse the args and call whatever function was selected - >>> args = parser.parse_args('foo 1 -x 2'.split()) + >>> args = parser.parse_args('multiply 7 -x 3'.split()) >>> args.func(args) - 2.0 + 21.0 >>> >>> # parse the args and call whatever function was selected - >>> args = parser.parse_args('bar XYZYX'.split()) + >>> args = parser.parse_args('parenthesize XYZYX'.split()) >>> args.func(args) ((XYZYX)) @@ -1589,12 +1632,12 @@ >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers(dest='subparser_name') - >>> subparser1 = subparsers.add_parser('1') + >>> subparser1 = subparsers.add_parser('7') >>> subparser1.add_argument('-x') - >>> subparser2 = subparsers.add_parser('2') + >>> subparser2 = subparsers.add_parser('3') >>> subparser2.add_argument('y') - >>> parser.parse_args(['2', 'frobble']) - Namespace(subparser_name='2', y='frobble') + >>> parser.parse_args(['3', 'frobble']) + Namespace(subparser_name='3', y='frobble') FileType objects @@ -1633,16 +1676,16 @@ default one, appropriate groups can be created using the :meth:`add_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] bar + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza', add_help=False) + >>> group = pizza_parser.add_argument_group('pizza making arguments') + >>> group.add_argument('--sauce', help='the sauce to use') + >>> group.add_argument('size', help='what size pizza to make') + >>> pizza_parser.print_help() + usage: makepizza [--sauce SAUCE] size - group: - bar bar help - --foo FOO foo help + pizza making arguments: + --sauce SAUCE the sauce to use + size what size pizza to make The :meth:`add_argument_group` method returns an argument group object which has an :meth:`~ArgumentParser.add_argument` method just like a regular @@ -1652,23 +1695,24 @@ accepts *title* and *description* arguments which can be used to customize 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] foo + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza', add_help=False) + >>> group1 = pizza_parser.add_argument_group('ingredients', 'What to use?') + >>> group1.add_argument('toppings', help='the toppings to put on') + >>> group2 = pizza_parser.add_argument_group('presentation', 'How to serve it?') + >>> group2.add_argument('--on-plates', action='store_true', + ... help="Serve pizza with paper plates") + >>> pizza_parser.print_help() + usage: makepizza [--on-plates] toppings - group1: - group1 description + ingredients: + What to use? - foo foo help + toppings the toppings to put on - group2: - group2 description + presentation: + How to serve it? - --bar BAR bar help + --on-plates Serve pizza with paper plates Note that any arguments not in your user-defined groups will end up back in the usual "positional arguments" and "optional arguments" sections. @@ -1683,29 +1727,29 @@ one of the arguments in the mutually exclusive group was present on the command 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 + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> group = pizza_parser.add_mutually_exclusive_group() + >>> group.add_argument('--tomato-sauce', action='store_true') + >>> group.add_argument('--bbq-sauce', action='store_true') + >>> pizza_parser.parse_args(['--tomato-sauce']) + Namespace(bbq_sauce=False, tomato_sauce=True) + >>> pizza_parser.parse_args(['--bbq-sauce']) + Namespace(bbq_sauce=True, tomato_sauce=False) + >>> pizza_parser.parse_args(['--tomato-sauce', '--bbq-sauce']) + usage: makepizza [-h] [--tomato-sauce | --bbq-sauce] + makepizza: error: argument --bbq-sauce: not allowed with argument --tomato-sauce The :meth:`add_mutually_exclusive_group` method also accepts a *required* argument, to indicate that at least one of the mutually exclusive arguments is 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 + >>> pizza_parser = argparse.ArgumentParser(prog='makepizza') + >>> group = pizza_parser.add_mutually_exclusive_group(required=True) + >>> group.add_argument('--tomato-sauce', action='store_true') + >>> group.add_argument('--bbq-sauce', action='store_true') + >>> pizza_parser.parse_args([]) + usage: makepizza [-h] (--tomato-sauce | --bbq-sauce) + makepizza: error: one of the arguments --tomato-sauce --bbq-sauce is required Note that currently mutually exclusive argument groups do not support the *title* and *description* arguments of @@ -1723,19 +1767,19 @@ attributes that are determined without any inspection of the command line to be 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) + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('price', type=float) + >>> pizza_parser.set_defaults(slices=8, sauce='tomato') + >>> pizza_parser.parse_args(['11.99']) + Namespace(price=11.99, sauce='tomato', slices=8) 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') + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--price', default=11.99) + >>> pizza_parser.set_defaults(price=24.22) + >>> pizza_parser.parse_args([]) + Namespace(price=24.22) Parser-level defaults can be particularly useful when working with multiple parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an @@ -1747,10 +1791,10 @@ :meth:`~ArgumentParser.add_argument` or by :meth:`~ArgumentParser.set_defaults`:: - >>> parser = argparse.ArgumentParser() - >>> parser.add_argument('--foo', default='badger') - >>> parser.get_default('foo') - 'badger' + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--sauce', default='tabasco') + >>> pizza_parser.get_default('sauce') + 'tabasco' Printing help @@ -1800,11 +1844,11 @@ :: - >>> 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']) + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--tomato-sauce', action='store_true') + >>> pizza_parser.add_argument('crust') + >>> pizza_parser.parse_known_args(['--tomato-sauce', '--zingy', 'stuffed', '1984']) + (Namespace(crust='stuffed', tomato_sauce=True), ['--zingy', '1984']) Customizing file parsing