diff -r 2367ec12da2d -r ea0e42d7551f Doc/library/argparse.rst --- a/Doc/library/argparse.rst Mon Jul 02 17:17:16 2012 -0700 +++ b/Doc/library/argparse.rst Sun Jul 08 23:01:08 2012 -0700 @@ -28,61 +28,89 @@ Example ------- -The following code is a Python program that takes a list of integers and -produces either the sum or the max:: +The following code is the argument parser for a Python program that takes +a list of line numbers, an optional 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, 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") + 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 + ... + text_file = open(args.file, 'r') + text_file_lines = [''] # "line 0" + text_file_lines.extend(text_file.readlines()) # start at "line 1" + + if args.line_numbers: + if len(args.line_numbers) == 1: + lines_to_print = (text_file_lines[args.line_numbers[0]]), + else: + # this picks the specified line_numbers out of the text_file_lines + from operator import itemgetter + lines_to_print = itemgetter(*args.line_numbers)(text_file_lines) + + print('Printing lines from... {0}!'.format(args.file)) + + for (i, line) in enumerate(lines_to_print): + if args.verbose: + print('Line #{0}: {1}'.format(args.line_numbers[i], line), end="") + else: + print(line, end="") + + +When run with the right arguments, it prints the specified lines:: + + $ printlinesfromfile.py 1 11 111 543 65432 + Printing lines from... /usr/share/dict/words! + Line #1: A + Line #11: Aaronic + Line #111: abbot + Line #543: absolutory + Line #65432: Euglenales 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 c + usage: printlinesfromfile.py [-h] [-f FILE] [-q] [N [N ...]] + printlinesfromfile.py: error: argument N: invalid int value: 'c' 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 +125,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 +146,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 +204,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 +225,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 +248,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='pizzaprogram', add_help=False) + >>> pizza_parser.add_argument('--size', help='what size pizza to make') + >>> pizza_parser.print_help() + usage: pizzaprogram [--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 +294,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 +323,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 +351,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 +368,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]) + >>> starnge_pizza_parser.add_argument('--crust') + >>> starnge_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 +465,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=float, + ... help="how man slices the pizza will be cut up into") + >>> pizza_parser.print_help() + usage: makepizza [-h] [--sauce str] float positional arguments: - float + float 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 +511,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 +552,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 +586,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 +601,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='pizzaprogram') + >>> pizza_parser.add_argument('--sauce', nargs='?') + >>> pizza_parser.add_argument('toppings', metavar='topping', nargs='+') + >>> pizza_parser.print_help() + usage: pizzaprogram [-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='pizzaprogram', + ... 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: pizzaprogram [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 +644,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 +678,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='pizzaprogram') + >>> 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: pizzaprogram [-h] [-s SIZE] crust + pizzaprogram: error: the following arguments are required: crust action ^^^^^^ @@ -685,9 +718,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 +728,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 +807,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 +832,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 +849,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 +878,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 +945,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,11 +984,11 @@ 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 @@ -964,9 +996,9 @@ writable file:: >>> parser = argparse.ArgumentParser() - >>> parser.add_argument('bar', type=argparse.FileType('w')) + >>> parser.add_argument('outfile', type=argparse.FileType('w')) >>> parser.parse_args(['out.txt']) - Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>) + 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 +1011,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 +1042,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='pizzaprogram') + >>> pizza_parser.add_argument('crust', + ... choices=['thin', 'deepdish', 'stuffed', 'regular']) + >>> pizza_parser.parse_args(['thin']) + Namespace(crust='thin') + >>> pizza_parser.parse_args(['chocolate']) + usage: pizzaprogram [-h] {thin,deepdish,stuffed,regular} + pizzaprogram: 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 +1076,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 +1102,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='pizzaprogram') + >>> 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: pizzaprogram [-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='pizzaprogram') + >>> pizza_parser.add_argument('slices', nargs='?', type=int, default=10, + ... help='number of slices %(prog)s should cut (default: %(default)s)') + >>> pizza_parser.print_help() + usage: pizzaprogram [-h] [slices] positional arguments: - bar the bar to frobble (default: 42) + slices number of slices pizzaprogram 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 +1139,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='pizzaprogram') + >>> pizza_parser.add_argument('--sauce', help=argparse.SUPPRESS) + >>> pizza_parser.print_help() + usage: pizzaprogram [-h] optional arguments: -h, --help show this help message and exit @@ -1119,7 +1151,7 @@ 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, @@ -1128,37 +1160,38 @@ 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 + >>> pizza_parser = argparse.ArgumentParser() + >>> pizza_parser.add_argument('--sauce') + >>> pizza_parser.add_argument('crust') + >>> 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 +1201,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 +1225,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 +1239,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='pizza_size_goes_here') + >>> pizza_parser.parse_args('--size veryverysmall'.split()) + Namespace(pizza_size_goes_here='veryverysmall') The parse_args() method