Lines Matching +full:is +full:- +full:arguments
1 :mod:`argparse` --- Parser for command-line options, arguments and sub-commands
5 :synopsis: Command-line option and argument parsing library.
13 --------------
18 introduction to Python command-line parsing, have a look at the
19 :ref:`argparse tutorial <argparse-tutorial>`.
21 The :mod:`argparse` module makes it easy to write user-friendly command-line
22 interfaces. The program defines what arguments it requires, and :mod:`argparse`
25 when users give the program invalid arguments.
29 -------
31 The following code is a Python program that takes a list of integers and
39 parser.add_argument('--sum', dest='accumulate', action='store_const',
46 Assuming the Python code above is saved into a file called ``prog.py``, it can
49 .. code-block:: shell-session
51 $ python prog.py -h
52 usage: prog.py [-h] [--sum] N [N ...]
56 positional arguments:
59 optional arguments:
60 -h, --help show this help message and exit
61 --sum sum the integers (default: find the max)
63 When run with the appropriate arguments, it prints either the sum or the max of
64 the command-line integers:
66 .. code-block:: shell-session
71 $ python prog.py 1 2 3 4 --sum
74 If invalid arguments are passed in, it will issue an error:
76 .. code-block:: shell-session
79 usage: prog.py [-h] [--sum] N [N ...]
88 The first step in using the :mod:`argparse` is creating an
97 Adding arguments
100 Filling an :class:`ArgumentParser` with information about program arguments is
103 on the command line and turn them into objects. This information is stored and
104 used when :meth:`~ArgumentParser.parse_args` is called. For example::
108 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
115 either the :func:`sum` function, if ``--sum`` was specified at the command line,
119 Parsing arguments
122 :class:`ArgumentParser` parses arguments through the
128 >>> parser.parse_args(['--sum', '7', '-1', '42'])
129 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
132 arguments, and the :class:`ArgumentParser` will automatically determine the
133 command-line arguments from :data:`sys.argv`.
137 ----------------------
142 prefix_chars='-', fromfile_prefix_chars=None, \
147 as keyword arguments. Each parameter has its own more detailed description
150 * prog_ - The name of the program (default: ``sys.argv[0]``)
152 * usage_ - The string describing the program usage (default: generated from
153 arguments added to parser)
155 * description_ - Text to display before the argument help (default: none)
157 * epilog_ - Text to display after the argument help (default: none)
159 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
162 * formatter_class_ - A class for customizing the help output
164 * prefix_chars_ - The set of characters that prefix optional arguments
165 (default: '-')
167 * fromfile_prefix_chars_ - The set of characters that prefix files from
168 which additional arguments should be read (default: ``None``)
170 * argument_default_ - The global default value for arguments
173 * conflict_handler_ - The strategy for resolving conflicting optionals
176 * add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)
185 how to display the name of the program in help messages. This default is almost
192 parser.add_argument('--foo', help='foo help')
198 .. code-block:: shell-session
200 $ python myprogram.py --help
201 usage: myprogram.py [-h] [--foo FOO]
203 optional arguments:
204 -h, --help show this help message and exit
205 --foo FOO foo help
207 $ python subdir/myprogram.py --help
208 usage: myprogram.py [-h] [--foo FOO]
210 optional arguments:
211 -h, --help show this help message and exit
212 --foo FOO foo help
219 usage: myprogram [-h]
221 optional arguments:
222 -h, --help show this help message and exit
225 ``prog=`` argument, is available to help messages using the ``%(prog)s`` format
231 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
233 usage: myprogram [-h] [--foo FOO]
235 optional arguments:
236 -h, --help show this help message and exit
237 --foo FOO foo of the myprogram program
244 arguments it contains::
247 >>> parser.add_argument('--foo', nargs='?', help='foo help')
250 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
252 positional arguments:
255 optional arguments:
256 -h, --help show this help message and exit
257 --foo [FOO] foo help
262 >>> parser.add_argument('--foo', nargs='?', help='foo help')
267 positional arguments:
270 optional arguments:
271 -h, --help show this help message and exit
272 --foo [FOO] foo help
274 The ``%(prog)s`` format specifier is available to fill in the program name in
283 what the program does and how it works. In help messages, the description is
284 displayed between the command-line usage string and the help messages for the
285 various arguments::
289 usage: argparse.py [-h]
293 optional arguments:
294 -h, --help show this help message and exit
296 By default, the description will be line-wrapped so that it fits within the
304 description of the arguments. Such text can be specified using the ``epilog=``
311 usage: argparse.py [-h]
315 optional arguments:
316 -h, --help show this help message and exit
320 As with the description_ argument, the ``epilog=`` text is by default
321 line-wrapped, but this behavior can be adjusted with the formatter_class_
328 Sometimes, several parsers share a common set of arguments. Rather than
329 repeating the definitions of these arguments, a single parser with all the
330 shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
336 >>> parent_parser.add_argument('--parent', type=int)
340 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
344 >>> bar_parser.add_argument('--bar')
345 >>> bar_parser.parse_args(['--bar', 'YYY'])
349 :class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
372 By default, :class:`ArgumentParser` objects line-wrap the description_ and
373 epilog_ texts in command-line help messages::
379 ... but that is okay''',
385 usage: PROG [-h]
387 this description was indented weird but that is okay
389 optional arguments:
390 -h, --help show this help message and exit
397 should not be line-wrapped::
404 ... --------------------------------
410 usage: PROG [-h]
413 --------------------------------
418 optional arguments:
419 -h, --help show this help message and exit
427 will add information about the default value of each of the arguments::
432 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
435 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
437 positional arguments:
440 optional arguments:
441 -h, --help show this help message and exit
442 --foo FOO FOO! (default: 42)
448 Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
454 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
460 The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
461 characters that does not include ``-`` will cause ``-f/--foo`` options to be
469 may make sense to keep the list of arguments in a file rather than typing it out
470 at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
471 :class:`ArgumentParser` constructor, then arguments that start with any of the
473 arguments they contain. For example::
476 ... fp.write('-f\nbar')
478 >>> parser.add_argument('-f')
479 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
482 Arguments read from a file must by default be one per line (but see also
485 line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
486 is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
489 arguments will never be treated as file references.
497 :meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
498 pairs. Sometimes however, it may be useful to specify a single parser-wide
499 default for arguments. This can be accomplished by passing the
505 >>> parser.add_argument('--foo')
507 >>> parser.parse_args(['--foo', '1', 'BAR'])
518 attempt is made to create an argument with an option string that is already in
522 >>> parser.add_argument('-f', '--foo', help='old foo help')
523 >>> parser.add_argument('--foo', help='new foo help')
526 ArgumentError: argument --foo: conflicting option string(s): --foo
529 older arguments with the same option string. To get this behavior, the value
534 >>> parser.add_argument('-f', '--foo', help='old foo help')
535 >>> parser.add_argument('--foo', help='new foo help')
537 usage: PROG [-h] [-f FOO] [--foo FOO]
539 optional arguments:
540 -h, --help show this help message and exit
541 -f FOO old foo help
542 --foo FOO new foo help
545 option strings are overridden. So, in the example above, the old ``-f/--foo``
546 action is retained as the ``-f`` action, because only the ``--foo`` option
559 parser.add_argument('--foo', help='foo help')
562 If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
565 .. code-block:: shell-session
567 $ python myprogram.py --help
568 usage: myprogram.py [-h] [--foo FOO]
570 optional arguments:
571 -h, --help show this help message and exit
572 --foo FOO foo help
579 >>> parser.add_argument('--foo', help='foo help')
581 usage: PROG [--foo FOO]
583 optional arguments:
584 --foo FOO foo help
586 The help option is typically ``-h/--help``. The exception to this is
587 if the ``prefix_chars=`` is specified and does not include ``-``, in
588 which case ``-h`` and ``--help`` are not valid options. In
589 this case, the first character in ``prefix_chars`` is used to prefix
596 optional arguments:
601 -------------------------
607 Define how a single command-line argument should be parsed. Each parameter
610 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
611 or ``-f, --foo``.
613 * action_ - The basic type of action to be taken when this argument is
616 * nargs_ - The number of command-line arguments that should be consumed.
618 * const_ - A constant value required by some action_ and nargs_ selections.
620 * default_ - The value produced if the argument is absent from the
623 * type_ - The type to which the command-line argument should be converted.
625 * choices_ - A container of the allowable values for the argument.
627 * required_ - Whether or not the command-line option may be omitted
630 * help_ - A brief description of what the argument does.
632 * metavar_ - A name for the argument in usage messages.
634 * dest_ - The name of the attribute to be added to the object returned by
644 argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
645 filenames, is expected. The first arguments passed to
650 >>> parser.add_argument('-f', '--foo')
656 When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
657 identified by the ``-`` prefix, and the remaining arguments will be assumed to
661 >>> parser.add_argument('-f', '--foo')
665 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
667 >>> parser.parse_args(['--foo', 'FOO'])
668 usage: PROG [-h] [-f FOO] bar
669 PROG: error: too few arguments
675 :class:`ArgumentParser` objects associate command-line arguments with actions. These
676 actions can do just about anything with the command-line arguments associated with
679 how the command-line arguments should be handled. The supplied actions are:
681 * ``'store'`` - This just stores the argument's value. This is the default
685 >>> parser.add_argument('--foo')
686 >>> parser.parse_args('--foo 1'.split())
689 * ``'store_const'`` - This stores the value specified by the const_ keyword
690 argument. The ``'store_const'`` action is most commonly used with
691 optional arguments that specify some sort of flag. For example::
694 >>> parser.add_argument('--foo', action='store_const', const=42)
695 >>> parser.parse_args(['--foo'])
698 * ``'store_true'`` and ``'store_false'`` - These are special cases of
704 >>> parser.add_argument('--foo', action='store_true')
705 >>> parser.add_argument('--bar', action='store_false')
706 >>> parser.add_argument('--baz', action='store_false')
707 >>> parser.parse_args('--foo --bar'.split())
710 * ``'append'`` - This stores a list, and appends each argument value to the
711 list. This is useful to allow an option to be specified multiple times.
715 >>> parser.add_argument('--foo', action='append')
716 >>> parser.parse_args('--foo 1 --foo 2'.split())
719 * ``'append_const'`` - This stores a list, and appends the value specified by
721 argument defaults to ``None``.) The ``'append_const'`` action is typically
722 useful when multiple arguments need to store constants to the same list. For
726 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
727 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
728 >>> parser.parse_args('--str --int'.split())
731 * ``'count'`` - This counts the number of times a keyword argument occurs. For
732 example, this is useful for increasing verbosity levels::
735 >>> parser.add_argument('--verbose', '-v', action='count')
736 >>> parser.parse_args(['-vvv'])
739 * ``'help'`` - This prints a complete help message for all the options in the
740 current parser and then exits. By default a help action is automatically
742 output is created.
744 * ``'version'`` - This expects a ``version=`` keyword argument in the
750 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
751 >>> parser.parse_args(['--version'])
756 this is to extend :class:`Action`, overriding the ``__call__`` method
763 ... if nargs is not None:
771 >>> parser.add_argument('--foo', action=FooAction)
773 >>> args = parser.parse_args('1 --foo 2'.split())
775 Namespace(bar='1', foo=None) '2' '--foo'
784 ArgumentParser objects usually associate a single command-line argument with a
786 different number of command-line arguments with a single action. The supported
789 * ``N`` (an integer). ``N`` arguments from the command line will be gathered
793 >>> parser.add_argument('--foo', nargs=2)
795 >>> parser.parse_args('c --foo a b'.split())
798 Note that ``nargs=1`` produces a list of one item. This is different from
799 the default, in which the item is produced by itself.
802 produced as a single item. If no command-line argument is present, the value from
803 default_ will be produced. Note that for optional arguments, there is an
804 additional case - the option string is present but not followed by a
805 command-line argument. In this case the value from const_ will be produced. Some
809 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
811 >>> parser.parse_args(['XX', '--foo', 'YY'])
813 >>> parser.parse_args(['XX', '--foo'])
818 One of the more common uses of ``nargs='?'`` is to allow optional input and
833 * ``'*'``. All command-line arguments present are gathered into a list. Note that
835 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
839 >>> parser.add_argument('--foo', nargs='*')
840 >>> parser.add_argument('--bar', nargs='*')
842 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
845 * ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
847 least one command-line argument present. For example::
854 usage: PROG [-h] foo [foo ...]
855 PROG: error: too few arguments
859 * ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
860 into a list. This is commonly useful for command line utilities that dispatch
864 >>> parser.add_argument('--foo')
867 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
868 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
870 If the ``nargs`` keyword argument is not provided, the number of arguments consumed
871 is determined by the action_. Generally this means a single command-line argument
878 The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
882 * When :meth:`~ArgumentParser.add_argument` is called with
887 * When :meth:`~ArgumentParser.add_argument` is called with option strings
888 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
889 argument that can be followed by zero or one command-line arguments.
890 When parsing the command line, if the option string is encountered with no
891 command-line argument following it, the value of ``const`` will be assumed instead.
901 All optional arguments and some positional arguments may be omitted at the
904 specifies what value should be used if the command-line argument is not present.
905 For optional arguments, the ``default`` value is used when the option string
909 >>> parser.add_argument('--foo', default=42)
910 >>> parser.parse_args(['--foo', '2'])
915 If the ``default`` value is a string, the parser parses the value as if it
916 were a command-line argument. In particular, the parser applies any type_
918 :class:`Namespace` return value. Otherwise, the parser uses the value as is::
921 >>> parser.add_argument('--length', default='10', type=int)
922 >>> parser.add_argument('--width', default=10.5, type=int)
926 For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
927 is used when no command-line argument was present::
938 command-line argument was not present.::
941 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
944 >>> parser.parse_args(['--foo', '1'])
951 By default, :class:`ArgumentParser` objects read command-line arguments in as simple
952 strings. However, quite often the command-line string should instead be
955 necessary type-checking and type conversions to be performed. Common built-in
965 ``type`` argument is applied to default arguments.
968 factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
984 ... msg = "%r is not a perfect square" % string
993 usage: PROG [-h] foo
994 PROG: error: argument foo: '7' is not a perfect square
1004 usage: PROG [-h] {5,6,7,8,9}
1013 Some command-line arguments should be selected from a restricted set of values.
1015 argument to :meth:`~ArgumentParser.add_argument`. When the command line is
1024 usage: game.py [-h] {rock,paper,scissors}
1028 Note that inclusion in the *choices* container is checked after any type_
1037 usage: doors.py [-h] {1,2,3}
1048 In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
1049 indicate *optional* arguments, which can always be omitted at the command line.
1054 >>> parser.add_argument('--foo', required=True)
1055 >>> parser.parse_args(['--foo', 'BAR'])
1058 usage: argparse.py [-h] [--foo FOO]
1059 argparse.py: error: option --foo is required
1061 As the example shows, if an option is marked as ``required``,
1062 :meth:`~ArgumentParser.parse_args` will report an error if that option is not
1074 The ``help`` value is a string containing a brief description of the argument.
1075 When a user requests help (usually by using ``-h`` or ``--help`` at the
1080 >>> parser.add_argument('--foo', action='store_true',
1084 >>> parser.parse_args(['-h'])
1085 usage: frobble [-h] [--foo] bar [bar ...]
1087 positional arguments:
1090 optional arguments:
1091 -h, --help show this help message and exit
1092 --foo foo the bars before frobbling
1096 specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1103 usage: frobble [-h] [bar]
1105 positional arguments:
1108 optional arguments:
1109 -h, --help show this help message and exit
1115 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1117 usage: frobble [-h]
1119 optional arguments:
1120 -h, --help show this help message and exit
1129 actions, the dest_ value is used directly, and for optional argument actions,
1130 the dest_ value is uppercased. So, a single positional argument with
1132 optional argument ``--foo`` that should be followed by a single command-line argument
1136 >>> parser.add_argument('--foo')
1138 >>> parser.parse_args('X --foo Y'.split())
1141 usage: [-h] [--foo FOO] bar
1143 positional arguments:
1146 optional arguments:
1147 -h, --help show this help message and exit
1148 --foo FOO
1153 >>> parser.add_argument('--foo', metavar='YYY')
1155 >>> parser.parse_args('X --foo Y'.split())
1158 usage: [-h] [--foo YYY] XXX
1160 positional arguments:
1163 optional arguments:
1164 -h, --help show this help message and exit
1165 --foo YYY
1167 Note that ``metavar`` only changes the *displayed* name - the name of the
1168 attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1173 arguments::
1176 >>> parser.add_argument('-x', nargs=2)
1177 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1179 usage: PROG [-h] [-x X X] [--foo bar baz]
1181 optional arguments:
1182 -h, --help show this help message and exit
1183 -x X X
1184 --foo bar baz
1192 attribute is determined by the ``dest`` keyword argument of
1194 ``dest`` is normally supplied as the first argument to
1202 For optional argument actions, the value of ``dest`` is normally inferred from
1204 taking the first long option string and stripping away the initial ``--``
1206 the first short option string by stripping the initial ``-`` character. Any
1207 internal ``-`` characters will be converted to ``_`` characters to make sure
1208 the string is a valid attribute name. The examples below illustrate this
1212 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1213 >>> parser.add_argument('-x', '-y')
1214 >>> parser.parse_args('-f 1 -x 2'.split())
1216 >>> parser.parse_args('--foo 1 -y 2'.split())
1222 >>> parser.add_argument('--foo', dest='bar')
1223 >>> parser.parse_args('--foo XXX'.split())
1230 which processes arguments from the command-line. Any object which follows this
1239 Action class must accept the two positional arguments plus any keyword arguments
1245 are defined is to call ``Action.__init__``.
1250 * ``parser`` - The ArgumentParser object which contains this action.
1252 * ``namespace`` - The :class:`Namespace` object that will be returned by
1256 * ``values`` - The associated command-line arguments, with any type conversions
1260 * ``option_string`` - The option string that was used to invoke this action.
1261 The ``option_string`` argument is optional, and will be absent if the action
1262 is associated with a positional argument.
1269 -----------------------
1280 * args_ - List of strings to parse. The default is taken from
1283 * namespace_ - An object to take the attributes. The default is a new empty
1292 option and its value are passed as two separate arguments::
1295 >>> parser.add_argument('-x')
1296 >>> parser.add_argument('--foo')
1297 >>> parser.parse_args(['-x', 'X'])
1299 >>> parser.parse_args(['--foo', 'FOO'])
1303 and value can also be passed as a single command-line argument, using ``=`` to
1306 >>> parser.parse_args(['--foo=FOO'])
1312 >>> parser.parse_args(['-xX'])
1315 Several short options can be joined together, using only a single ``-`` prefix,
1319 >>> parser.add_argument('-x', action='store_true')
1320 >>> parser.add_argument('-y', action='store_true')
1321 >>> parser.add_argument('-z')
1322 >>> parser.parse_args(['-xyzZ'])
1326 Invalid arguments
1331 wrong number of positional arguments, etc. When it encounters such an error,
1335 >>> parser.add_argument('--foo', type=int)
1339 >>> parser.parse_args(['--foo', 'spam'])
1340 usage: PROG [-h] [--foo FOO] [bar]
1341 PROG: error: argument --foo: invalid int value: 'spam'
1344 >>> parser.parse_args(['--bar'])
1345 usage: PROG [-h] [--foo FOO] [bar]
1346 PROG: error: no such option: --bar
1348 >>> # wrong number of arguments
1350 usage: PROG [-h] [--foo FOO] [bar]
1351 PROG: error: extra arguments found: badger
1354 Arguments containing ``-``
1359 ambiguous. For example, the command-line argument ``-1`` could either be an
1361 The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
1362 arguments may only begin with ``-`` if they look like negative numbers and
1366 >>> parser.add_argument('-x')
1369 >>> # no negative number options, so -1 is a positional argument
1370 >>> parser.parse_args(['-x', '-1'])
1371 Namespace(foo=None, x='-1')
1373 >>> # no negative number options, so -1 and -5 are positional arguments
1374 >>> parser.parse_args(['-x', '-1', '-5'])
1375 Namespace(foo='-5', x='-1')
1378 >>> parser.add_argument('-1', dest='one')
1381 >>> # negative number options present, so -1 is an option
1382 >>> parser.parse_args(['-1', 'X'])
1385 >>> # negative number options present, so -2 is an option
1386 >>> parser.parse_args(['-2'])
1387 usage: PROG [-h] [-1 ONE] [foo]
1388 PROG: error: no such option: -2
1390 >>> # negative number options present, so both -1s are options
1391 >>> parser.parse_args(['-1', '-1'])
1392 usage: PROG [-h] [-1 ONE] [foo]
1393 PROG: error: argument -1: expected one argument
1395 If you have positional arguments that must begin with ``-`` and don't look
1396 like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1397 :meth:`~ArgumentParser.parse_args` that everything after that is a positional
1400 >>> parser.parse_args(['--', '-f'])
1401 Namespace(foo='-f', one=None)
1403 .. _prefix-matching:
1409 abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
1413 >>> parser.add_argument('-bacon')
1414 >>> parser.add_argument('-badger')
1415 >>> parser.parse_args('-bac MMM'.split())
1417 >>> parser.parse_args('-bad WOOD'.split())
1419 >>> parser.parse_args('-ba BA'.split())
1420 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1421 PROG: error: ambiguous option: -ba could match -badger, -bacon
1423 An error is produced for arguments that could produce more than one options.
1430 Sometimes it may be useful to have an ArgumentParser parse arguments other than those
1432 :meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1440 ... '--sum', dest='accumulate', action='store_const', const=sum,
1443 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1444 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
1445 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1457 This class is deliberately simple, just an :class:`object` subclass with a
1458 readable string representation. If you prefer to have dict-like view of the
1462 >>> parser.add_argument('--foo')
1463 >>> args = parser.parse_args(['--foo', 'BAR'])
1476 >>> parser.add_argument('--foo')
1477 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1483 ---------------
1485 Sub-commands
1493 Many programs split up their functionality into a number of sub-commands,
1494 for example, the ``svn`` program can invoke sub-commands like ``svn
1497 different functions which require different kinds of command-line arguments.
1498 :class:`ArgumentParser` supports the creation of such sub-commands with the
1499 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1500 called with no arguments and returns a special action object. This object
1502 command name and any :class:`ArgumentParser` constructor arguments, and
1507 * title - title for the sub-parser group in help output; by default
1508 "subcommands" if description is provided, otherwise uses title for
1509 positional arguments
1511 * description - description for the sub-parser group in help output, by
1514 * prog - usage information that will be displayed with sub-command help,
1515 by default the name of the program and any positional arguments before the
1518 * parser_class - class which will be used to create sub-parser instances, by
1521 * action_ - the basic type of action to be taken when this argument is
1524 * dest_ - name of the attribute under which sub-command name will be
1525 stored; by default ``None`` and no value is stored
1527 * help_ - help for sub-parser group in help output, by default ``None``
1529 * metavar_ - string presenting available sub-commands in help; by default it
1530 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
1534 >>> # create the top-level parser
1536 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1537 >>> subparsers = parser.add_subparsers(help='sub-command help')
1545 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1550 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1556 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1557 present, and when the ``b`` command is specified, only the ``foo`` and
1560 Similarly, when a help message is requested from a subparser, only the help
1568 >>> parser.parse_args(['--help'])
1569 usage: PROG [-h] [--foo] {a,b} ...
1571 positional arguments:
1572 {a,b} sub-command help
1576 optional arguments:
1577 -h, --help show this help message and exit
1578 --foo foo help
1580 >>> parser.parse_args(['a', '--help'])
1581 usage: PROG a [-h] bar
1583 positional arguments:
1586 optional arguments:
1587 -h, --help show this help message and exit
1589 >>> parser.parse_args(['b', '--help'])
1590 usage: PROG b [-h] [--baz {X,Y,Z}]
1592 optional arguments:
1593 -h, --help show this help message and exit
1594 --baz {X,Y,Z} baz help
1597 keyword arguments. When either is present, the subparser's commands will
1606 >>> parser.parse_args(['-h'])
1607 usage: [-h] {foo,bar} ...
1609 optional arguments:
1610 -h, --help show this help message and exit
1618 One particularly effective way of handling sub-commands is to combine the use
1623 >>> # sub-command functions
1630 >>> # create the top-level parser
1636 >>> parser_foo.add_argument('-x', type=int, default=1)
1646 >>> args = parser.parse_args('foo 1 -x 2'.split())
1656 appropriate function after argument parsing is complete. Associating
1657 functions with actions like this is typically the easiest way to handle the
1658 different actions for each of your subparsers. However, if it is necessary
1665 >>> subparser1.add_argument('-x')
1678 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1679 :class:`FileType` objects as their type will open command-line arguments as files
1683 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1684 >>> parser.parse_args(['--output', 'out'])
1687 FileType objects understand the pseudo-argument ``'-'`` and automatically
1693 >>> parser.parse_args(['-'])
1702 By default, :class:`ArgumentParser` groups command-line arguments into
1703 "positional arguments" and "optional arguments" when displaying help
1704 messages. When there is a better conceptual grouping of arguments than this
1710 >>> group.add_argument('--foo', help='foo help')
1713 usage: PROG [--foo FOO] bar
1717 --foo FOO foo help
1721 :class:`ArgumentParser`. When an argument is added to the group, the parser
1724 accepts *title* and *description* arguments which can be used to
1731 >>> group2.add_argument('--bar', help='bar help')
1733 usage: PROG [--bar BAR] foo
1743 --bar BAR bar help
1745 Note that any arguments not in your user-defined groups will end up back
1746 in the usual "positional arguments" and "optional arguments" sections.
1755 one of the arguments in the mutually exclusive group was present on the
1760 >>> group.add_argument('--foo', action='store_true')
1761 >>> group.add_argument('--bar', action='store_false')
1762 >>> parser.parse_args(['--foo'])
1764 >>> parser.parse_args(['--bar'])
1766 >>> parser.parse_args(['--foo', '--bar'])
1767 usage: PROG [-h] [--foo | --bar]
1768 PROG: error: argument --bar: not allowed with argument --foo
1771 argument, to indicate that at least one of the mutually exclusive arguments
1772 is required::
1776 >>> group.add_argument('--foo', action='store_true')
1777 >>> group.add_argument('--bar', action='store_false')
1779 usage: PROG [-h] (--foo | --bar)
1780 PROG: error: one of the arguments --foo --bar is required
1783 *title* and *description* arguments of
1793 will be fully determined by inspecting the command-line arguments and the argument
1804 Note that parser-level defaults always override argument-level defaults::
1807 >>> parser.add_argument('--foo', default='bar')
1812 Parser-level defaults can be particularly useful when working with multiple
1823 >>> parser.add_argument('--foo', default='badger')
1838 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
1844 arguments registered with the :class:`ArgumentParser`. If *file* is
1845 ``None``, :data:`sys.stdout` is assumed.
1858 information about the arguments registered with the :class:`ArgumentParser`.
1866 Sometimes a script may only parse a few of the command-line arguments, passing
1867 the remaining arguments on to another script or program. In these cases, the
1870 extra arguments are present. Instead, it returns a two item tuple containing
1876 >>> parser.add_argument('--foo', action='store_true')
1878 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1879 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1882 :ref:`Prefix matching <prefix-matching>` rules apply to
1885 arguments list.
1893 Arguments that are read from a file (see the *fromfile_prefix_chars*
1898 This method takes a single argument *arg_line* which is a string read from
1899 the argument file. It returns a list of arguments parsed from this string.
1900 The method is called once per line read from the argument file, in order.
1902 A useful override of this method is one that treats each space-separated word
1923 .. _argparse-from-optparse:
1926 -----------------------
1932 :mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1938 * Handling positional arguments.
1939 * Supporting sub-commands.
1941 * Handling zero-or-more and one-or-more style arguments.
1952 calls for the positional arguments. Keep in mind that what was previously
1953 called ``options``, now in the :mod:`argparse` context is called ``args``.
1960 * Replace callback actions and the ``callback_*`` keyword arguments with
1961 ``type`` or ``action`` arguments.
1963 * Replace string names for ``type`` keyword arguments with the corresponding
1970 * Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1971 the standard Python syntax to use dictionaries to format strings, that is,
1975 ``parser.add_argument('--version', action='version', version='<the version>')``.