1:mod:`argparse` --- Parser for command-line options, arguments and sub-commands 2=============================================================================== 3 4.. module:: argparse 5 :synopsis: Command-line option and argument parsing library. 6 7.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com> 8.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com> 9 10.. versionadded:: 3.2 11 12**Source code:** :source:`Lib/argparse.py` 13 14-------------- 15 16.. sidebar:: Tutorial 17 18 This page contains the API reference information. For a more gentle 19 introduction to Python command-line parsing, have a look at the 20 :ref:`argparse tutorial <argparse-tutorial>`. 21 22The :mod:`argparse` module makes it easy to write user-friendly command-line 23interfaces. The program defines what arguments it requires, and :mod:`argparse` 24will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse` 25module also automatically generates help and usage messages and issues errors 26when users give the program invalid arguments. 27 28 29Example 30------- 31 32The following code is a Python program that takes a list of integers and 33produces either the sum or the max:: 34 35 import argparse 36 37 parser = argparse.ArgumentParser(description='Process some integers.') 38 parser.add_argument('integers', metavar='N', type=int, nargs='+', 39 help='an integer for the accumulator') 40 parser.add_argument('--sum', dest='accumulate', action='store_const', 41 const=sum, default=max, 42 help='sum the integers (default: find the max)') 43 44 args = parser.parse_args() 45 print(args.accumulate(args.integers)) 46 47Assuming the Python code above is saved into a file called ``prog.py``, it can 48be run at the command line and provides useful help messages: 49 50.. code-block:: shell-session 51 52 $ python prog.py -h 53 usage: prog.py [-h] [--sum] N [N ...] 54 55 Process some integers. 56 57 positional arguments: 58 N an integer for the accumulator 59 60 optional arguments: 61 -h, --help show this help message and exit 62 --sum sum the integers (default: find the max) 63 64When run with the appropriate arguments, it prints either the sum or the max of 65the command-line integers: 66 67.. code-block:: shell-session 68 69 $ python prog.py 1 2 3 4 70 4 71 72 $ python prog.py 1 2 3 4 --sum 73 10 74 75If invalid arguments are passed in, it will issue an error: 76 77.. code-block:: shell-session 78 79 $ python prog.py a b c 80 usage: prog.py [-h] [--sum] N [N ...] 81 prog.py: error: argument N: invalid int value: 'a' 82 83The following sections walk you through this example. 84 85 86Creating a parser 87^^^^^^^^^^^^^^^^^ 88 89The first step in using the :mod:`argparse` is creating an 90:class:`ArgumentParser` object:: 91 92 >>> parser = argparse.ArgumentParser(description='Process some integers.') 93 94The :class:`ArgumentParser` object will hold all the information necessary to 95parse the command line into Python data types. 96 97 98Adding arguments 99^^^^^^^^^^^^^^^^ 100 101Filling an :class:`ArgumentParser` with information about program arguments is 102done by making calls to the :meth:`~ArgumentParser.add_argument` method. 103Generally, these calls tell the :class:`ArgumentParser` how to take the strings 104on the command line and turn them into objects. This information is stored and 105used when :meth:`~ArgumentParser.parse_args` is called. For example:: 106 107 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+', 108 ... help='an integer for the accumulator') 109 >>> parser.add_argument('--sum', dest='accumulate', action='store_const', 110 ... const=sum, default=max, 111 ... help='sum the integers (default: find the max)') 112 113Later, calling :meth:`~ArgumentParser.parse_args` will return an object with 114two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute 115will be a list of one or more ints, and the ``accumulate`` attribute will be 116either the :func:`sum` function, if ``--sum`` was specified at the command line, 117or the :func:`max` function if it was not. 118 119 120Parsing arguments 121^^^^^^^^^^^^^^^^^ 122 123:class:`ArgumentParser` parses arguments through the 124:meth:`~ArgumentParser.parse_args` method. This will inspect the command line, 125convert each argument to the appropriate type and then invoke the appropriate action. 126In most cases, this means a simple :class:`Namespace` object will be built up from 127attributes parsed out of the command line:: 128 129 >>> parser.parse_args(['--sum', '7', '-1', '42']) 130 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42]) 131 132In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no 133arguments, and the :class:`ArgumentParser` will automatically determine the 134command-line arguments from :data:`sys.argv`. 135 136 137ArgumentParser objects 138---------------------- 139 140.. class:: ArgumentParser(prog=None, usage=None, description=None, \ 141 epilog=None, parents=[], \ 142 formatter_class=argparse.HelpFormatter, \ 143 prefix_chars='-', fromfile_prefix_chars=None, \ 144 argument_default=None, conflict_handler='error', \ 145 add_help=True, allow_abbrev=True) 146 147 Create a new :class:`ArgumentParser` object. All parameters should be passed 148 as keyword arguments. Each parameter has its own more detailed description 149 below, but in short they are: 150 151 * prog_ - The name of the program (default: ``sys.argv[0]``) 152 153 * usage_ - The string describing the program usage (default: generated from 154 arguments added to parser) 155 156 * description_ - Text to display before the argument help (default: none) 157 158 * epilog_ - Text to display after the argument help (default: none) 159 160 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should 161 also be included 162 163 * formatter_class_ - A class for customizing the help output 164 165 * prefix_chars_ - The set of characters that prefix optional arguments 166 (default: '-') 167 168 * fromfile_prefix_chars_ - The set of characters that prefix files from 169 which additional arguments should be read (default: ``None``) 170 171 * argument_default_ - The global default value for arguments 172 (default: ``None``) 173 174 * conflict_handler_ - The strategy for resolving conflicting optionals 175 (usually unnecessary) 176 177 * add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``) 178 179 * allow_abbrev_ - Allows long options to be abbreviated if the 180 abbreviation is unambiguous. (default: ``True``) 181 182 .. versionchanged:: 3.5 183 *allow_abbrev* parameter was added. 184 185The following sections describe how each of these are used. 186 187 188prog 189^^^^ 190 191By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine 192how to display the name of the program in help messages. This default is almost 193always desirable because it will make the help messages match how the program was 194invoked on the command line. For example, consider a file named 195``myprogram.py`` with the following code:: 196 197 import argparse 198 parser = argparse.ArgumentParser() 199 parser.add_argument('--foo', help='foo help') 200 args = parser.parse_args() 201 202The help for this program will display ``myprogram.py`` as the program name 203(regardless of where the program was invoked from): 204 205.. code-block:: shell-session 206 207 $ python myprogram.py --help 208 usage: myprogram.py [-h] [--foo FOO] 209 210 optional arguments: 211 -h, --help show this help message and exit 212 --foo FOO foo help 213 $ cd .. 214 $ python subdir/myprogram.py --help 215 usage: myprogram.py [-h] [--foo FOO] 216 217 optional arguments: 218 -h, --help show this help message and exit 219 --foo FOO foo help 220 221To change this default behavior, another value can be supplied using the 222``prog=`` argument to :class:`ArgumentParser`:: 223 224 >>> parser = argparse.ArgumentParser(prog='myprogram') 225 >>> parser.print_help() 226 usage: myprogram [-h] 227 228 optional arguments: 229 -h, --help show this help message and exit 230 231Note that the program name, whether determined from ``sys.argv[0]`` or from the 232``prog=`` argument, is available to help messages using the ``%(prog)s`` format 233specifier. 234 235:: 236 237 >>> parser = argparse.ArgumentParser(prog='myprogram') 238 >>> parser.add_argument('--foo', help='foo of the %(prog)s program') 239 >>> parser.print_help() 240 usage: myprogram [-h] [--foo FOO] 241 242 optional arguments: 243 -h, --help show this help message and exit 244 --foo FOO foo of the myprogram program 245 246 247usage 248^^^^^ 249 250By default, :class:`ArgumentParser` calculates the usage message from the 251arguments it contains:: 252 253 >>> parser = argparse.ArgumentParser(prog='PROG') 254 >>> parser.add_argument('--foo', nargs='?', help='foo help') 255 >>> parser.add_argument('bar', nargs='+', help='bar help') 256 >>> parser.print_help() 257 usage: PROG [-h] [--foo [FOO]] bar [bar ...] 258 259 positional arguments: 260 bar bar help 261 262 optional arguments: 263 -h, --help show this help message and exit 264 --foo [FOO] foo help 265 266The default message can be overridden with the ``usage=`` keyword argument:: 267 268 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') 269 >>> parser.add_argument('--foo', nargs='?', help='foo help') 270 >>> parser.add_argument('bar', nargs='+', help='bar help') 271 >>> parser.print_help() 272 usage: PROG [options] 273 274 positional arguments: 275 bar bar help 276 277 optional arguments: 278 -h, --help show this help message and exit 279 --foo [FOO] foo help 280 281The ``%(prog)s`` format specifier is available to fill in the program name in 282your usage messages. 283 284 285description 286^^^^^^^^^^^ 287 288Most calls to the :class:`ArgumentParser` constructor will use the 289``description=`` keyword argument. This argument gives a brief description of 290what the program does and how it works. In help messages, the description is 291displayed between the command-line usage string and the help messages for the 292various arguments:: 293 294 >>> parser = argparse.ArgumentParser(description='A foo that bars') 295 >>> parser.print_help() 296 usage: argparse.py [-h] 297 298 A foo that bars 299 300 optional arguments: 301 -h, --help show this help message and exit 302 303By default, the description will be line-wrapped so that it fits within the 304given space. To change this behavior, see the formatter_class_ argument. 305 306 307epilog 308^^^^^^ 309 310Some programs like to display additional description of the program after the 311description of the arguments. Such text can be specified using the ``epilog=`` 312argument to :class:`ArgumentParser`:: 313 314 >>> parser = argparse.ArgumentParser( 315 ... description='A foo that bars', 316 ... epilog="And that's how you'd foo a bar") 317 >>> parser.print_help() 318 usage: argparse.py [-h] 319 320 A foo that bars 321 322 optional arguments: 323 -h, --help show this help message and exit 324 325 And that's how you'd foo a bar 326 327As with the description_ argument, the ``epilog=`` text is by default 328line-wrapped, but this behavior can be adjusted with the formatter_class_ 329argument to :class:`ArgumentParser`. 330 331 332parents 333^^^^^^^ 334 335Sometimes, several parsers share a common set of arguments. Rather than 336repeating the definitions of these arguments, a single parser with all the 337shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser` 338can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser` 339objects, collects all the positional and optional actions from them, and adds 340these actions to the :class:`ArgumentParser` object being constructed:: 341 342 >>> parent_parser = argparse.ArgumentParser(add_help=False) 343 >>> parent_parser.add_argument('--parent', type=int) 344 345 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser]) 346 >>> foo_parser.add_argument('foo') 347 >>> foo_parser.parse_args(['--parent', '2', 'XXX']) 348 Namespace(foo='XXX', parent=2) 349 350 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser]) 351 >>> bar_parser.add_argument('--bar') 352 >>> bar_parser.parse_args(['--bar', 'YYY']) 353 Namespace(bar='YYY', parent=None) 354 355Note that most parent parsers will specify ``add_help=False``. Otherwise, the 356:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent 357and one in the child) and raise an error. 358 359.. note:: 360 You must fully initialize the parsers before passing them via ``parents=``. 361 If you change the parent parsers after the child parser, those changes will 362 not be reflected in the child. 363 364 365formatter_class 366^^^^^^^^^^^^^^^ 367 368:class:`ArgumentParser` objects allow the help formatting to be customized by 369specifying an alternate formatting class. Currently, there are four such 370classes: 371 372.. class:: RawDescriptionHelpFormatter 373 RawTextHelpFormatter 374 ArgumentDefaultsHelpFormatter 375 MetavarTypeHelpFormatter 376 377:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give 378more control over how textual descriptions are displayed. 379By default, :class:`ArgumentParser` objects line-wrap the description_ and 380epilog_ texts in command-line help messages:: 381 382 >>> parser = argparse.ArgumentParser( 383 ... prog='PROG', 384 ... description='''this description 385 ... was indented weird 386 ... but that is okay''', 387 ... epilog=''' 388 ... likewise for this epilog whose whitespace will 389 ... be cleaned up and whose words will be wrapped 390 ... across a couple lines''') 391 >>> parser.print_help() 392 usage: PROG [-h] 393 394 this description was indented weird but that is okay 395 396 optional arguments: 397 -h, --help show this help message and exit 398 399 likewise for this epilog whose whitespace will be cleaned up and whose words 400 will be wrapped across a couple lines 401 402Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=`` 403indicates that description_ and epilog_ are already correctly formatted and 404should not be line-wrapped:: 405 406 >>> parser = argparse.ArgumentParser( 407 ... prog='PROG', 408 ... formatter_class=argparse.RawDescriptionHelpFormatter, 409 ... description=textwrap.dedent('''\ 410 ... Please do not mess up this text! 411 ... -------------------------------- 412 ... I have indented it 413 ... exactly the way 414 ... I want it 415 ... ''')) 416 >>> parser.print_help() 417 usage: PROG [-h] 418 419 Please do not mess up this text! 420 -------------------------------- 421 I have indented it 422 exactly the way 423 I want it 424 425 optional arguments: 426 -h, --help show this help message and exit 427 428:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text, 429including argument descriptions. 430 431:class:`ArgumentDefaultsHelpFormatter` automatically adds information about 432default values to each of the argument help messages:: 433 434 >>> parser = argparse.ArgumentParser( 435 ... prog='PROG', 436 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter) 437 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!') 438 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!') 439 >>> parser.print_help() 440 usage: PROG [-h] [--foo FOO] [bar [bar ...]] 441 442 positional arguments: 443 bar BAR! (default: [1, 2, 3]) 444 445 optional arguments: 446 -h, --help show this help message and exit 447 --foo FOO FOO! (default: 42) 448 449:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each 450argument as the display name for its values (rather than using the dest_ 451as the regular formatter does):: 452 453 >>> parser = argparse.ArgumentParser( 454 ... prog='PROG', 455 ... formatter_class=argparse.MetavarTypeHelpFormatter) 456 >>> parser.add_argument('--foo', type=int) 457 >>> parser.add_argument('bar', type=float) 458 >>> parser.print_help() 459 usage: PROG [-h] [--foo int] float 460 461 positional arguments: 462 float 463 464 optional arguments: 465 -h, --help show this help message and exit 466 --foo int 467 468 469prefix_chars 470^^^^^^^^^^^^ 471 472Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``. 473Parsers that need to support different or additional prefix 474characters, e.g. for options 475like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument 476to the ArgumentParser constructor:: 477 478 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+') 479 >>> parser.add_argument('+f') 480 >>> parser.add_argument('++bar') 481 >>> parser.parse_args('+f X ++bar Y'.split()) 482 Namespace(bar='Y', f='X') 483 484The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of 485characters that does not include ``-`` will cause ``-f/--foo`` options to be 486disallowed. 487 488 489fromfile_prefix_chars 490^^^^^^^^^^^^^^^^^^^^^ 491 492Sometimes, for example when dealing with a particularly long argument lists, it 493may make sense to keep the list of arguments in a file rather than typing it out 494at the command line. If the ``fromfile_prefix_chars=`` argument is given to the 495:class:`ArgumentParser` constructor, then arguments that start with any of the 496specified characters will be treated as files, and will be replaced by the 497arguments they contain. For example:: 498 499 >>> with open('args.txt', 'w') as fp: 500 ... fp.write('-f\nbar') 501 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@') 502 >>> parser.add_argument('-f') 503 >>> parser.parse_args(['-f', 'foo', '@args.txt']) 504 Namespace(f='bar') 505 506Arguments read from a file must by default be one per line (but see also 507:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they 508were in the same place as the original file referencing argument on the command 509line. So in the example above, the expression ``['-f', 'foo', '@args.txt']`` 510is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``. 511 512The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that 513arguments will never be treated as file references. 514 515 516argument_default 517^^^^^^^^^^^^^^^^ 518 519Generally, argument defaults are specified either by passing a default to 520:meth:`~ArgumentParser.add_argument` or by calling the 521:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value 522pairs. Sometimes however, it may be useful to specify a single parser-wide 523default for arguments. This can be accomplished by passing the 524``argument_default=`` keyword argument to :class:`ArgumentParser`. For example, 525to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args` 526calls, we supply ``argument_default=SUPPRESS``:: 527 528 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) 529 >>> parser.add_argument('--foo') 530 >>> parser.add_argument('bar', nargs='?') 531 >>> parser.parse_args(['--foo', '1', 'BAR']) 532 Namespace(bar='BAR', foo='1') 533 >>> parser.parse_args([]) 534 Namespace() 535 536.. _allow_abbrev: 537 538allow_abbrev 539^^^^^^^^^^^^ 540 541Normally, when you pass an argument list to the 542:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`, 543it :ref:`recognizes abbreviations <prefix-matching>` of long options. 544 545This feature can be disabled by setting ``allow_abbrev`` to ``False``:: 546 547 >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False) 548 >>> parser.add_argument('--foobar', action='store_true') 549 >>> parser.add_argument('--foonley', action='store_false') 550 >>> parser.parse_args(['--foon']) 551 usage: PROG [-h] [--foobar] [--foonley] 552 PROG: error: unrecognized arguments: --foon 553 554.. versionadded:: 3.5 555 556 557conflict_handler 558^^^^^^^^^^^^^^^^ 559 560:class:`ArgumentParser` objects do not allow two actions with the same option 561string. By default, :class:`ArgumentParser` objects raise an exception if an 562attempt is made to create an argument with an option string that is already in 563use:: 564 565 >>> parser = argparse.ArgumentParser(prog='PROG') 566 >>> parser.add_argument('-f', '--foo', help='old foo help') 567 >>> parser.add_argument('--foo', help='new foo help') 568 Traceback (most recent call last): 569 .. 570 ArgumentError: argument --foo: conflicting option string(s): --foo 571 572Sometimes (e.g. when using parents_) it may be useful to simply override any 573older arguments with the same option string. To get this behavior, the value 574``'resolve'`` can be supplied to the ``conflict_handler=`` argument of 575:class:`ArgumentParser`:: 576 577 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve') 578 >>> parser.add_argument('-f', '--foo', help='old foo help') 579 >>> parser.add_argument('--foo', help='new foo help') 580 >>> parser.print_help() 581 usage: PROG [-h] [-f FOO] [--foo FOO] 582 583 optional arguments: 584 -h, --help show this help message and exit 585 -f FOO old foo help 586 --foo FOO new foo help 587 588Note that :class:`ArgumentParser` objects only remove an action if all of its 589option strings are overridden. So, in the example above, the old ``-f/--foo`` 590action is retained as the ``-f`` action, because only the ``--foo`` option 591string was overridden. 592 593 594add_help 595^^^^^^^^ 596 597By default, ArgumentParser objects add an option which simply displays 598the parser's help message. For example, consider a file named 599``myprogram.py`` containing the following code:: 600 601 import argparse 602 parser = argparse.ArgumentParser() 603 parser.add_argument('--foo', help='foo help') 604 args = parser.parse_args() 605 606If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser 607help will be printed: 608 609.. code-block:: shell-session 610 611 $ python myprogram.py --help 612 usage: myprogram.py [-h] [--foo FOO] 613 614 optional arguments: 615 -h, --help show this help message and exit 616 --foo FOO foo help 617 618Occasionally, it may be useful to disable the addition of this help option. 619This can be achieved by passing ``False`` as the ``add_help=`` argument to 620:class:`ArgumentParser`:: 621 622 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) 623 >>> parser.add_argument('--foo', help='foo help') 624 >>> parser.print_help() 625 usage: PROG [--foo FOO] 626 627 optional arguments: 628 --foo FOO foo help 629 630The help option is typically ``-h/--help``. The exception to this is 631if the ``prefix_chars=`` is specified and does not include ``-``, in 632which case ``-h`` and ``--help`` are not valid options. In 633this case, the first character in ``prefix_chars`` is used to prefix 634the help options:: 635 636 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/') 637 >>> parser.print_help() 638 usage: PROG [+h] 639 640 optional arguments: 641 +h, ++help show this help message and exit 642 643 644The add_argument() method 645------------------------- 646 647.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \ 648 [const], [default], [type], [choices], [required], \ 649 [help], [metavar], [dest]) 650 651 Define how a single command-line argument should be parsed. Each parameter 652 has its own more detailed description below, but in short they are: 653 654 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo`` 655 or ``-f, --foo``. 656 657 * action_ - The basic type of action to be taken when this argument is 658 encountered at the command line. 659 660 * nargs_ - The number of command-line arguments that should be consumed. 661 662 * const_ - A constant value required by some action_ and nargs_ selections. 663 664 * default_ - The value produced if the argument is absent from the 665 command line. 666 667 * type_ - The type to which the command-line argument should be converted. 668 669 * choices_ - A container of the allowable values for the argument. 670 671 * required_ - Whether or not the command-line option may be omitted 672 (optionals only). 673 674 * help_ - A brief description of what the argument does. 675 676 * metavar_ - A name for the argument in usage messages. 677 678 * dest_ - The name of the attribute to be added to the object returned by 679 :meth:`parse_args`. 680 681The following sections describe how each of these are used. 682 683 684name or flags 685^^^^^^^^^^^^^ 686 687The :meth:`~ArgumentParser.add_argument` method must know whether an optional 688argument, like ``-f`` or ``--foo``, or a positional argument, like a list of 689filenames, is expected. The first arguments passed to 690:meth:`~ArgumentParser.add_argument` must therefore be either a series of 691flags, or a simple argument name. For example, an optional argument could 692be created like:: 693 694 >>> parser.add_argument('-f', '--foo') 695 696while a positional argument could be created like:: 697 698 >>> parser.add_argument('bar') 699 700When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be 701identified by the ``-`` prefix, and the remaining arguments will be assumed to 702be positional:: 703 704 >>> parser = argparse.ArgumentParser(prog='PROG') 705 >>> parser.add_argument('-f', '--foo') 706 >>> parser.add_argument('bar') 707 >>> parser.parse_args(['BAR']) 708 Namespace(bar='BAR', foo=None) 709 >>> parser.parse_args(['BAR', '--foo', 'FOO']) 710 Namespace(bar='BAR', foo='FOO') 711 >>> parser.parse_args(['--foo', 'FOO']) 712 usage: PROG [-h] [-f FOO] bar 713 PROG: error: too few arguments 714 715 716action 717^^^^^^ 718 719:class:`ArgumentParser` objects associate command-line arguments with actions. These 720actions can do just about anything with the command-line arguments associated with 721them, though most actions simply add an attribute to the object returned by 722:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies 723how the command-line arguments should be handled. The supplied actions are: 724 725* ``'store'`` - This just stores the argument's value. This is the default 726 action. For example:: 727 728 >>> parser = argparse.ArgumentParser() 729 >>> parser.add_argument('--foo') 730 >>> parser.parse_args('--foo 1'.split()) 731 Namespace(foo='1') 732 733* ``'store_const'`` - This stores the value specified by the const_ keyword 734 argument. The ``'store_const'`` action is most commonly used with 735 optional arguments that specify some sort of flag. For example:: 736 737 >>> parser = argparse.ArgumentParser() 738 >>> parser.add_argument('--foo', action='store_const', const=42) 739 >>> parser.parse_args(['--foo']) 740 Namespace(foo=42) 741 742* ``'store_true'`` and ``'store_false'`` - These are special cases of 743 ``'store_const'`` used for storing the values ``True`` and ``False`` 744 respectively. In addition, they create default values of ``False`` and 745 ``True`` respectively. For example:: 746 747 >>> parser = argparse.ArgumentParser() 748 >>> parser.add_argument('--foo', action='store_true') 749 >>> parser.add_argument('--bar', action='store_false') 750 >>> parser.add_argument('--baz', action='store_false') 751 >>> parser.parse_args('--foo --bar'.split()) 752 Namespace(foo=True, bar=False, baz=True) 753 754* ``'append'`` - This stores a list, and appends each argument value to the 755 list. This is useful to allow an option to be specified multiple times. 756 Example usage:: 757 758 >>> parser = argparse.ArgumentParser() 759 >>> parser.add_argument('--foo', action='append') 760 >>> parser.parse_args('--foo 1 --foo 2'.split()) 761 Namespace(foo=['1', '2']) 762 763* ``'append_const'`` - This stores a list, and appends the value specified by 764 the const_ keyword argument to the list. (Note that the const_ keyword 765 argument defaults to ``None``.) The ``'append_const'`` action is typically 766 useful when multiple arguments need to store constants to the same list. For 767 example:: 768 769 >>> parser = argparse.ArgumentParser() 770 >>> parser.add_argument('--str', dest='types', action='append_const', const=str) 771 >>> parser.add_argument('--int', dest='types', action='append_const', const=int) 772 >>> parser.parse_args('--str --int'.split()) 773 Namespace(types=[<class 'str'>, <class 'int'>]) 774 775* ``'count'`` - This counts the number of times a keyword argument occurs. For 776 example, this is useful for increasing verbosity levels:: 777 778 >>> parser = argparse.ArgumentParser() 779 >>> parser.add_argument('--verbose', '-v', action='count') 780 >>> parser.parse_args(['-vvv']) 781 Namespace(verbose=3) 782 783* ``'help'`` - This prints a complete help message for all the options in the 784 current parser and then exits. By default a help action is automatically 785 added to the parser. See :class:`ArgumentParser` for details of how the 786 output is created. 787 788* ``'version'`` - This expects a ``version=`` keyword argument in the 789 :meth:`~ArgumentParser.add_argument` call, and prints version information 790 and exits when invoked:: 791 792 >>> import argparse 793 >>> parser = argparse.ArgumentParser(prog='PROG') 794 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0') 795 >>> parser.parse_args(['--version']) 796 PROG 2.0 797 798You may also specify an arbitrary action by passing an Action subclass or 799other object that implements the same interface. The recommended way to do 800this is to extend :class:`Action`, overriding the ``__call__`` method 801and optionally the ``__init__`` method. 802 803An example of a custom action:: 804 805 >>> class FooAction(argparse.Action): 806 ... def __init__(self, option_strings, dest, nargs=None, **kwargs): 807 ... if nargs is not None: 808 ... raise ValueError("nargs not allowed") 809 ... super(FooAction, self).__init__(option_strings, dest, **kwargs) 810 ... def __call__(self, parser, namespace, values, option_string=None): 811 ... print('%r %r %r' % (namespace, values, option_string)) 812 ... setattr(namespace, self.dest, values) 813 ... 814 >>> parser = argparse.ArgumentParser() 815 >>> parser.add_argument('--foo', action=FooAction) 816 >>> parser.add_argument('bar', action=FooAction) 817 >>> args = parser.parse_args('1 --foo 2'.split()) 818 Namespace(bar=None, foo=None) '1' None 819 Namespace(bar='1', foo=None) '2' '--foo' 820 >>> args 821 Namespace(bar='1', foo='2') 822 823For more details, see :class:`Action`. 824 825nargs 826^^^^^ 827 828ArgumentParser objects usually associate a single command-line argument with a 829single action to be taken. The ``nargs`` keyword argument associates a 830different number of command-line arguments with a single action. The supported 831values are: 832 833* ``N`` (an integer). ``N`` arguments from the command line will be gathered 834 together into a list. For example:: 835 836 >>> parser = argparse.ArgumentParser() 837 >>> parser.add_argument('--foo', nargs=2) 838 >>> parser.add_argument('bar', nargs=1) 839 >>> parser.parse_args('c --foo a b'.split()) 840 Namespace(bar=['c'], foo=['a', 'b']) 841 842 Note that ``nargs=1`` produces a list of one item. This is different from 843 the default, in which the item is produced by itself. 844 845* ``'?'``. One argument will be consumed from the command line if possible, and 846 produced as a single item. If no command-line argument is present, the value from 847 default_ will be produced. Note that for optional arguments, there is an 848 additional case - the option string is present but not followed by a 849 command-line argument. In this case the value from const_ will be produced. Some 850 examples to illustrate this:: 851 852 >>> parser = argparse.ArgumentParser() 853 >>> parser.add_argument('--foo', nargs='?', const='c', default='d') 854 >>> parser.add_argument('bar', nargs='?', default='d') 855 >>> parser.parse_args(['XX', '--foo', 'YY']) 856 Namespace(bar='XX', foo='YY') 857 >>> parser.parse_args(['XX', '--foo']) 858 Namespace(bar='XX', foo='c') 859 >>> parser.parse_args([]) 860 Namespace(bar='d', foo='d') 861 862 One of the more common uses of ``nargs='?'`` is to allow optional input and 863 output files:: 864 865 >>> parser = argparse.ArgumentParser() 866 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), 867 ... default=sys.stdin) 868 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), 869 ... default=sys.stdout) 870 >>> parser.parse_args(['input.txt', 'output.txt']) 871 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>, 872 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>) 873 >>> parser.parse_args([]) 874 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>, 875 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>) 876 877* ``'*'``. All command-line arguments present are gathered into a list. Note that 878 it generally doesn't make much sense to have more than one positional argument 879 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is 880 possible. For example:: 881 882 >>> parser = argparse.ArgumentParser() 883 >>> parser.add_argument('--foo', nargs='*') 884 >>> parser.add_argument('--bar', nargs='*') 885 >>> parser.add_argument('baz', nargs='*') 886 >>> parser.parse_args('a b --foo x y --bar 1 2'.split()) 887 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y']) 888 889* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a 890 list. Additionally, an error message will be generated if there wasn't at 891 least one command-line argument present. For example:: 892 893 >>> parser = argparse.ArgumentParser(prog='PROG') 894 >>> parser.add_argument('foo', nargs='+') 895 >>> parser.parse_args(['a', 'b']) 896 Namespace(foo=['a', 'b']) 897 >>> parser.parse_args([]) 898 usage: PROG [-h] foo [foo ...] 899 PROG: error: too few arguments 900 901* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered 902 into a list. This is commonly useful for command line utilities that dispatch 903 to other command line utilities:: 904 905 >>> parser = argparse.ArgumentParser(prog='PROG') 906 >>> parser.add_argument('--foo') 907 >>> parser.add_argument('command') 908 >>> parser.add_argument('args', nargs=argparse.REMAINDER) 909 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())) 910 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B') 911 912If the ``nargs`` keyword argument is not provided, the number of arguments consumed 913is determined by the action_. Generally this means a single command-line argument 914will be consumed and a single item (not a list) will be produced. 915 916 917const 918^^^^^ 919 920The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold 921constant values that are not read from the command line but are required for 922the various :class:`ArgumentParser` actions. The two most common uses of it are: 923 924* When :meth:`~ArgumentParser.add_argument` is called with 925 ``action='store_const'`` or ``action='append_const'``. These actions add the 926 ``const`` value to one of the attributes of the object returned by 927 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples. 928 929* When :meth:`~ArgumentParser.add_argument` is called with option strings 930 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional 931 argument that can be followed by zero or one command-line arguments. 932 When parsing the command line, if the option string is encountered with no 933 command-line argument following it, the value of ``const`` will be assumed instead. 934 See the nargs_ description for examples. 935 936With the ``'store_const'`` and ``'append_const'`` actions, the ``const`` 937keyword argument must be given. For other actions, it defaults to ``None``. 938 939 940default 941^^^^^^^ 942 943All optional arguments and some positional arguments may be omitted at the 944command line. The ``default`` keyword argument of 945:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``, 946specifies what value should be used if the command-line argument is not present. 947For optional arguments, the ``default`` value is used when the option string 948was not present at the command line:: 949 950 >>> parser = argparse.ArgumentParser() 951 >>> parser.add_argument('--foo', default=42) 952 >>> parser.parse_args(['--foo', '2']) 953 Namespace(foo='2') 954 >>> parser.parse_args([]) 955 Namespace(foo=42) 956 957If the ``default`` value is a string, the parser parses the value as if it 958were a command-line argument. In particular, the parser applies any type_ 959conversion argument, if provided, before setting the attribute on the 960:class:`Namespace` return value. Otherwise, the parser uses the value as is:: 961 962 >>> parser = argparse.ArgumentParser() 963 >>> parser.add_argument('--length', default='10', type=int) 964 >>> parser.add_argument('--width', default=10.5, type=int) 965 >>> parser.parse_args() 966 Namespace(length=10, width=10.5) 967 968For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value 969is used when no command-line argument was present:: 970 971 >>> parser = argparse.ArgumentParser() 972 >>> parser.add_argument('foo', nargs='?', default=42) 973 >>> parser.parse_args(['a']) 974 Namespace(foo='a') 975 >>> parser.parse_args([]) 976 Namespace(foo=42) 977 978 979Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the 980command-line argument was not present.:: 981 982 >>> parser = argparse.ArgumentParser() 983 >>> parser.add_argument('--foo', default=argparse.SUPPRESS) 984 >>> parser.parse_args([]) 985 Namespace() 986 >>> parser.parse_args(['--foo', '1']) 987 Namespace(foo='1') 988 989 990type 991^^^^ 992 993By default, :class:`ArgumentParser` objects read command-line arguments in as simple 994strings. However, quite often the command-line string should instead be 995interpreted as another type, like a :class:`float` or :class:`int`. The 996``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any 997necessary type-checking and type conversions to be performed. Common built-in 998types and functions can be used directly as the value of the ``type`` argument:: 999 1000 >>> parser = argparse.ArgumentParser() 1001 >>> parser.add_argument('foo', type=int) 1002 >>> parser.add_argument('bar', type=open) 1003 >>> parser.parse_args('2 temp.txt'.split()) 1004 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2) 1005 1006See the section on the default_ keyword argument for information on when the 1007``type`` argument is applied to default arguments. 1008 1009To ease the use of various types of files, the argparse module provides the 1010factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and 1011``errors=`` arguments of the :func:`open` function. For example, 1012``FileType('w')`` can be used to create a writable file:: 1013 1014 >>> parser = argparse.ArgumentParser() 1015 >>> parser.add_argument('bar', type=argparse.FileType('w')) 1016 >>> parser.parse_args(['out.txt']) 1017 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>) 1018 1019``type=`` can take any callable that takes a single string argument and returns 1020the converted value:: 1021 1022 >>> def perfect_square(string): 1023 ... value = int(string) 1024 ... sqrt = math.sqrt(value) 1025 ... if sqrt != int(sqrt): 1026 ... msg = "%r is not a perfect square" % string 1027 ... raise argparse.ArgumentTypeError(msg) 1028 ... return value 1029 ... 1030 >>> parser = argparse.ArgumentParser(prog='PROG') 1031 >>> parser.add_argument('foo', type=perfect_square) 1032 >>> parser.parse_args(['9']) 1033 Namespace(foo=9) 1034 >>> parser.parse_args(['7']) 1035 usage: PROG [-h] foo 1036 PROG: error: argument foo: '7' is not a perfect square 1037 1038The choices_ keyword argument may be more convenient for type checkers that 1039simply check against a range of values:: 1040 1041 >>> parser = argparse.ArgumentParser(prog='PROG') 1042 >>> parser.add_argument('foo', type=int, choices=range(5, 10)) 1043 >>> parser.parse_args(['7']) 1044 Namespace(foo=7) 1045 >>> parser.parse_args(['11']) 1046 usage: PROG [-h] {5,6,7,8,9} 1047 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9) 1048 1049See the choices_ section for more details. 1050 1051 1052choices 1053^^^^^^^ 1054 1055Some command-line arguments should be selected from a restricted set of values. 1056These can be handled by passing a container object as the *choices* keyword 1057argument to :meth:`~ArgumentParser.add_argument`. When the command line is 1058parsed, argument values will be checked, and an error message will be displayed 1059if the argument was not one of the acceptable values:: 1060 1061 >>> parser = argparse.ArgumentParser(prog='game.py') 1062 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors']) 1063 >>> parser.parse_args(['rock']) 1064 Namespace(move='rock') 1065 >>> parser.parse_args(['fire']) 1066 usage: game.py [-h] {rock,paper,scissors} 1067 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock', 1068 'paper', 'scissors') 1069 1070Note that inclusion in the *choices* container is checked after any type_ 1071conversions have been performed, so the type of the objects in the *choices* 1072container should match the type_ specified:: 1073 1074 >>> parser = argparse.ArgumentParser(prog='doors.py') 1075 >>> parser.add_argument('door', type=int, choices=range(1, 4)) 1076 >>> print(parser.parse_args(['3'])) 1077 Namespace(door=3) 1078 >>> parser.parse_args(['4']) 1079 usage: doors.py [-h] {1,2,3} 1080 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3) 1081 1082Any object that supports the ``in`` operator can be passed as the *choices* 1083value, so :class:`dict` objects, :class:`set` objects, custom containers, 1084etc. are all supported. 1085 1086 1087required 1088^^^^^^^^ 1089 1090In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar`` 1091indicate *optional* arguments, which can always be omitted at the command line. 1092To make an option *required*, ``True`` can be specified for the ``required=`` 1093keyword argument to :meth:`~ArgumentParser.add_argument`:: 1094 1095 >>> parser = argparse.ArgumentParser() 1096 >>> parser.add_argument('--foo', required=True) 1097 >>> parser.parse_args(['--foo', 'BAR']) 1098 Namespace(foo='BAR') 1099 >>> parser.parse_args([]) 1100 usage: argparse.py [-h] [--foo FOO] 1101 argparse.py: error: option --foo is required 1102 1103As the example shows, if an option is marked as ``required``, 1104:meth:`~ArgumentParser.parse_args` will report an error if that option is not 1105present at the command line. 1106 1107.. note:: 1108 1109 Required options are generally considered bad form because users expect 1110 *options* to be *optional*, and thus they should be avoided when possible. 1111 1112 1113help 1114^^^^ 1115 1116The ``help`` value is a string containing a brief description of the argument. 1117When a user requests help (usually by using ``-h`` or ``--help`` at the 1118command line), these ``help`` descriptions will be displayed with each 1119argument:: 1120 1121 >>> parser = argparse.ArgumentParser(prog='frobble') 1122 >>> parser.add_argument('--foo', action='store_true', 1123 ... help='foo the bars before frobbling') 1124 >>> parser.add_argument('bar', nargs='+', 1125 ... help='one of the bars to be frobbled') 1126 >>> parser.parse_args(['-h']) 1127 usage: frobble [-h] [--foo] bar [bar ...] 1128 1129 positional arguments: 1130 bar one of the bars to be frobbled 1131 1132 optional arguments: 1133 -h, --help show this help message and exit 1134 --foo foo the bars before frobbling 1135 1136The ``help`` strings can include various format specifiers to avoid repetition 1137of things like the program name or the argument default_. The available 1138specifiers include the program name, ``%(prog)s`` and most keyword arguments to 1139:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.:: 1140 1141 >>> parser = argparse.ArgumentParser(prog='frobble') 1142 >>> parser.add_argument('bar', nargs='?', type=int, default=42, 1143 ... help='the bar to %(prog)s (default: %(default)s)') 1144 >>> parser.print_help() 1145 usage: frobble [-h] [bar] 1146 1147 positional arguments: 1148 bar the bar to frobble (default: 42) 1149 1150 optional arguments: 1151 -h, --help show this help message and exit 1152 1153As the help string supports %-formatting, if you want a literal ``%`` to appear 1154in the help string, you must escape it as ``%%``. 1155 1156:mod:`argparse` supports silencing the help entry for certain options, by 1157setting the ``help`` value to ``argparse.SUPPRESS``:: 1158 1159 >>> parser = argparse.ArgumentParser(prog='frobble') 1160 >>> parser.add_argument('--foo', help=argparse.SUPPRESS) 1161 >>> parser.print_help() 1162 usage: frobble [-h] 1163 1164 optional arguments: 1165 -h, --help show this help message and exit 1166 1167 1168metavar 1169^^^^^^^ 1170 1171When :class:`ArgumentParser` generates help messages, it needs some way to refer 1172to each expected argument. By default, ArgumentParser objects use the dest_ 1173value as the "name" of each object. By default, for positional argument 1174actions, the dest_ value is used directly, and for optional argument actions, 1175the dest_ value is uppercased. So, a single positional argument with 1176``dest='bar'`` will be referred to as ``bar``. A single 1177optional argument ``--foo`` that should be followed by a single command-line argument 1178will be referred to as ``FOO``. An example:: 1179 1180 >>> parser = argparse.ArgumentParser() 1181 >>> parser.add_argument('--foo') 1182 >>> parser.add_argument('bar') 1183 >>> parser.parse_args('X --foo Y'.split()) 1184 Namespace(bar='X', foo='Y') 1185 >>> parser.print_help() 1186 usage: [-h] [--foo FOO] bar 1187 1188 positional arguments: 1189 bar 1190 1191 optional arguments: 1192 -h, --help show this help message and exit 1193 --foo FOO 1194 1195An alternative name can be specified with ``metavar``:: 1196 1197 >>> parser = argparse.ArgumentParser() 1198 >>> parser.add_argument('--foo', metavar='YYY') 1199 >>> parser.add_argument('bar', metavar='XXX') 1200 >>> parser.parse_args('X --foo Y'.split()) 1201 Namespace(bar='X', foo='Y') 1202 >>> parser.print_help() 1203 usage: [-h] [--foo YYY] XXX 1204 1205 positional arguments: 1206 XXX 1207 1208 optional arguments: 1209 -h, --help show this help message and exit 1210 --foo YYY 1211 1212Note that ``metavar`` only changes the *displayed* name - the name of the 1213attribute on the :meth:`~ArgumentParser.parse_args` object is still determined 1214by the dest_ value. 1215 1216Different values of ``nargs`` may cause the metavar to be used multiple times. 1217Providing a tuple to ``metavar`` specifies a different display for each of the 1218arguments:: 1219 1220 >>> parser = argparse.ArgumentParser(prog='PROG') 1221 >>> parser.add_argument('-x', nargs=2) 1222 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz')) 1223 >>> parser.print_help() 1224 usage: PROG [-h] [-x X X] [--foo bar baz] 1225 1226 optional arguments: 1227 -h, --help show this help message and exit 1228 -x X X 1229 --foo bar baz 1230 1231 1232dest 1233^^^^ 1234 1235Most :class:`ArgumentParser` actions add some value as an attribute of the 1236object returned by :meth:`~ArgumentParser.parse_args`. The name of this 1237attribute is determined by the ``dest`` keyword argument of 1238:meth:`~ArgumentParser.add_argument`. For positional argument actions, 1239``dest`` is normally supplied as the first argument to 1240:meth:`~ArgumentParser.add_argument`:: 1241 1242 >>> parser = argparse.ArgumentParser() 1243 >>> parser.add_argument('bar') 1244 >>> parser.parse_args(['XXX']) 1245 Namespace(bar='XXX') 1246 1247For optional argument actions, the value of ``dest`` is normally inferred from 1248the option strings. :class:`ArgumentParser` generates the value of ``dest`` by 1249taking the first long option string and stripping away the initial ``--`` 1250string. If no long option strings were supplied, ``dest`` will be derived from 1251the first short option string by stripping the initial ``-`` character. Any 1252internal ``-`` characters will be converted to ``_`` characters to make sure 1253the string is a valid attribute name. The examples below illustrate this 1254behavior:: 1255 1256 >>> parser = argparse.ArgumentParser() 1257 >>> parser.add_argument('-f', '--foo-bar', '--foo') 1258 >>> parser.add_argument('-x', '-y') 1259 >>> parser.parse_args('-f 1 -x 2'.split()) 1260 Namespace(foo_bar='1', x='2') 1261 >>> parser.parse_args('--foo 1 -y 2'.split()) 1262 Namespace(foo_bar='1', x='2') 1263 1264``dest`` allows a custom attribute name to be provided:: 1265 1266 >>> parser = argparse.ArgumentParser() 1267 >>> parser.add_argument('--foo', dest='bar') 1268 >>> parser.parse_args('--foo XXX'.split()) 1269 Namespace(bar='XXX') 1270 1271Action classes 1272^^^^^^^^^^^^^^ 1273 1274Action classes implement the Action API, a callable which returns a callable 1275which processes arguments from the command-line. Any object which follows 1276this API may be passed as the ``action`` parameter to 1277:meth:`add_argument`. 1278 1279.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \ 1280 type=None, choices=None, required=False, help=None, \ 1281 metavar=None) 1282 1283Action objects are used by an ArgumentParser to represent the information 1284needed to parse a single argument from one or more strings from the 1285command line. The Action class must accept the two positional arguments 1286plus any keyword arguments passed to :meth:`ArgumentParser.add_argument` 1287except for the ``action`` itself. 1288 1289Instances of Action (or return value of any callable to the ``action`` 1290parameter) should have attributes "dest", "option_strings", "default", "type", 1291"required", "help", etc. defined. The easiest way to ensure these attributes 1292are defined is to call ``Action.__init__``. 1293 1294Action instances should be callable, so subclasses must override the 1295``__call__`` method, which should accept four parameters: 1296 1297* ``parser`` - The ArgumentParser object which contains this action. 1298 1299* ``namespace`` - The :class:`Namespace` object that will be returned by 1300 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this 1301 object using :func:`setattr`. 1302 1303* ``values`` - The associated command-line arguments, with any type conversions 1304 applied. Type conversions are specified with the type_ keyword argument to 1305 :meth:`~ArgumentParser.add_argument`. 1306 1307* ``option_string`` - The option string that was used to invoke this action. 1308 The ``option_string`` argument is optional, and will be absent if the action 1309 is associated with a positional argument. 1310 1311The ``__call__`` method may perform arbitrary actions, but will typically set 1312attributes on the ``namespace`` based on ``dest`` and ``values``. 1313 1314 1315The parse_args() method 1316----------------------- 1317 1318.. method:: ArgumentParser.parse_args(args=None, namespace=None) 1319 1320 Convert argument strings to objects and assign them as attributes of the 1321 namespace. Return the populated namespace. 1322 1323 Previous calls to :meth:`add_argument` determine exactly what objects are 1324 created and how they are assigned. See the documentation for 1325 :meth:`add_argument` for details. 1326 1327 By default, the argument strings are taken from :data:`sys.argv`, and a new empty 1328 :class:`Namespace` object is created for the attributes. 1329 1330 1331Option value syntax 1332^^^^^^^^^^^^^^^^^^^ 1333 1334The :meth:`~ArgumentParser.parse_args` method supports several ways of 1335specifying the value of an option (if it takes one). In the simplest case, the 1336option and its value are passed as two separate arguments:: 1337 1338 >>> parser = argparse.ArgumentParser(prog='PROG') 1339 >>> parser.add_argument('-x') 1340 >>> parser.add_argument('--foo') 1341 >>> parser.parse_args(['-x', 'X']) 1342 Namespace(foo=None, x='X') 1343 >>> parser.parse_args(['--foo', 'FOO']) 1344 Namespace(foo='FOO', x=None) 1345 1346For long options (options with names longer than a single character), the option 1347and value can also be passed as a single command-line argument, using ``=`` to 1348separate them:: 1349 1350 >>> parser.parse_args(['--foo=FOO']) 1351 Namespace(foo='FOO', x=None) 1352 1353For short options (options only one character long), the option and its value 1354can be concatenated:: 1355 1356 >>> parser.parse_args(['-xX']) 1357 Namespace(foo=None, x='X') 1358 1359Several short options can be joined together, using only a single ``-`` prefix, 1360as long as only the last option (or none of them) requires a value:: 1361 1362 >>> parser = argparse.ArgumentParser(prog='PROG') 1363 >>> parser.add_argument('-x', action='store_true') 1364 >>> parser.add_argument('-y', action='store_true') 1365 >>> parser.add_argument('-z') 1366 >>> parser.parse_args(['-xyzZ']) 1367 Namespace(x=True, y=True, z='Z') 1368 1369 1370Invalid arguments 1371^^^^^^^^^^^^^^^^^ 1372 1373While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a 1374variety of errors, including ambiguous options, invalid types, invalid options, 1375wrong number of positional arguments, etc. When it encounters such an error, 1376it exits and prints the error along with a usage message:: 1377 1378 >>> parser = argparse.ArgumentParser(prog='PROG') 1379 >>> parser.add_argument('--foo', type=int) 1380 >>> parser.add_argument('bar', nargs='?') 1381 1382 >>> # invalid type 1383 >>> parser.parse_args(['--foo', 'spam']) 1384 usage: PROG [-h] [--foo FOO] [bar] 1385 PROG: error: argument --foo: invalid int value: 'spam' 1386 1387 >>> # invalid option 1388 >>> parser.parse_args(['--bar']) 1389 usage: PROG [-h] [--foo FOO] [bar] 1390 PROG: error: no such option: --bar 1391 1392 >>> # wrong number of arguments 1393 >>> parser.parse_args(['spam', 'badger']) 1394 usage: PROG [-h] [--foo FOO] [bar] 1395 PROG: error: extra arguments found: badger 1396 1397 1398Arguments containing ``-`` 1399^^^^^^^^^^^^^^^^^^^^^^^^^^ 1400 1401The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever 1402the user has clearly made a mistake, but some situations are inherently 1403ambiguous. For example, the command-line argument ``-1`` could either be an 1404attempt to specify an option or an attempt to provide a positional argument. 1405The :meth:`~ArgumentParser.parse_args` method is cautious here: positional 1406arguments may only begin with ``-`` if they look like negative numbers and 1407there are no options in the parser that look like negative numbers:: 1408 1409 >>> parser = argparse.ArgumentParser(prog='PROG') 1410 >>> parser.add_argument('-x') 1411 >>> parser.add_argument('foo', nargs='?') 1412 1413 >>> # no negative number options, so -1 is a positional argument 1414 >>> parser.parse_args(['-x', '-1']) 1415 Namespace(foo=None, x='-1') 1416 1417 >>> # no negative number options, so -1 and -5 are positional arguments 1418 >>> parser.parse_args(['-x', '-1', '-5']) 1419 Namespace(foo='-5', x='-1') 1420 1421 >>> parser = argparse.ArgumentParser(prog='PROG') 1422 >>> parser.add_argument('-1', dest='one') 1423 >>> parser.add_argument('foo', nargs='?') 1424 1425 >>> # negative number options present, so -1 is an option 1426 >>> parser.parse_args(['-1', 'X']) 1427 Namespace(foo=None, one='X') 1428 1429 >>> # negative number options present, so -2 is an option 1430 >>> parser.parse_args(['-2']) 1431 usage: PROG [-h] [-1 ONE] [foo] 1432 PROG: error: no such option: -2 1433 1434 >>> # negative number options present, so both -1s are options 1435 >>> parser.parse_args(['-1', '-1']) 1436 usage: PROG [-h] [-1 ONE] [foo] 1437 PROG: error: argument -1: expected one argument 1438 1439If you have positional arguments that must begin with ``-`` and don't look 1440like negative numbers, you can insert the pseudo-argument ``'--'`` which tells 1441:meth:`~ArgumentParser.parse_args` that everything after that is a positional 1442argument:: 1443 1444 >>> parser.parse_args(['--', '-f']) 1445 Namespace(foo='-f', one=None) 1446 1447.. _prefix-matching: 1448 1449Argument abbreviations (prefix matching) 1450^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1451 1452The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>` 1453allows long options to be abbreviated to a prefix, if the abbreviation is 1454unambiguous (the prefix matches a unique option):: 1455 1456 >>> parser = argparse.ArgumentParser(prog='PROG') 1457 >>> parser.add_argument('-bacon') 1458 >>> parser.add_argument('-badger') 1459 >>> parser.parse_args('-bac MMM'.split()) 1460 Namespace(bacon='MMM', badger=None) 1461 >>> parser.parse_args('-bad WOOD'.split()) 1462 Namespace(bacon=None, badger='WOOD') 1463 >>> parser.parse_args('-ba BA'.split()) 1464 usage: PROG [-h] [-bacon BACON] [-badger BADGER] 1465 PROG: error: ambiguous option: -ba could match -badger, -bacon 1466 1467An error is produced for arguments that could produce more than one options. 1468This feature can be disabled by setting :ref:`allow_abbrev` to ``False``. 1469 1470 1471Beyond ``sys.argv`` 1472^^^^^^^^^^^^^^^^^^^ 1473 1474Sometimes it may be useful to have an ArgumentParser parse arguments other than those 1475of :data:`sys.argv`. This can be accomplished by passing a list of strings to 1476:meth:`~ArgumentParser.parse_args`. This is useful for testing at the 1477interactive prompt:: 1478 1479 >>> parser = argparse.ArgumentParser() 1480 >>> parser.add_argument( 1481 ... 'integers', metavar='int', type=int, choices=range(10), 1482 ... nargs='+', help='an integer in the range 0..9') 1483 >>> parser.add_argument( 1484 ... '--sum', dest='accumulate', action='store_const', const=sum, 1485 ... default=max, help='sum the integers (default: find the max)') 1486 >>> parser.parse_args(['1', '2', '3', '4']) 1487 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4]) 1488 >>> parser.parse_args(['1', '2', '3', '4', '--sum']) 1489 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4]) 1490 1491 1492The Namespace object 1493^^^^^^^^^^^^^^^^^^^^ 1494 1495.. class:: Namespace 1496 1497 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create 1498 an object holding attributes and return it. 1499 1500This class is deliberately simple, just an :class:`object` subclass with a 1501readable string representation. If you prefer to have dict-like view of the 1502attributes, you can use the standard Python idiom, :func:`vars`:: 1503 1504 >>> parser = argparse.ArgumentParser() 1505 >>> parser.add_argument('--foo') 1506 >>> args = parser.parse_args(['--foo', 'BAR']) 1507 >>> vars(args) 1508 {'foo': 'BAR'} 1509 1510It may also be useful to have an :class:`ArgumentParser` assign attributes to an 1511already existing object, rather than a new :class:`Namespace` object. This can 1512be achieved by specifying the ``namespace=`` keyword argument:: 1513 1514 >>> class C: 1515 ... pass 1516 ... 1517 >>> c = C() 1518 >>> parser = argparse.ArgumentParser() 1519 >>> parser.add_argument('--foo') 1520 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c) 1521 >>> c.foo 1522 'BAR' 1523 1524 1525Other utilities 1526--------------- 1527 1528Sub-commands 1529^^^^^^^^^^^^ 1530 1531.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \ 1532 [parser_class], [action], \ 1533 [option_string], [dest], [help], \ 1534 [metavar]) 1535 1536 Many programs split up their functionality into a number of sub-commands, 1537 for example, the ``svn`` program can invoke sub-commands like ``svn 1538 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality 1539 this way can be a particularly good idea when a program performs several 1540 different functions which require different kinds of command-line arguments. 1541 :class:`ArgumentParser` supports the creation of such sub-commands with the 1542 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally 1543 called with no arguments and returns a special action object. This object 1544 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a 1545 command name and any :class:`ArgumentParser` constructor arguments, and 1546 returns an :class:`ArgumentParser` object that can be modified as usual. 1547 1548 Description of parameters: 1549 1550 * title - title for the sub-parser group in help output; by default 1551 "subcommands" if description is provided, otherwise uses title for 1552 positional arguments 1553 1554 * description - description for the sub-parser group in help output, by 1555 default ``None`` 1556 1557 * prog - usage information that will be displayed with sub-command help, 1558 by default the name of the program and any positional arguments before the 1559 subparser argument 1560 1561 * parser_class - class which will be used to create sub-parser instances, by 1562 default the class of the current parser (e.g. ArgumentParser) 1563 1564 * action_ - the basic type of action to be taken when this argument is 1565 encountered at the command line 1566 1567 * dest_ - name of the attribute under which sub-command name will be 1568 stored; by default ``None`` and no value is stored 1569 1570 * help_ - help for sub-parser group in help output, by default ``None`` 1571 1572 * metavar_ - string presenting available sub-commands in help; by default it 1573 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..} 1574 1575 Some example usage:: 1576 1577 >>> # create the top-level parser 1578 >>> parser = argparse.ArgumentParser(prog='PROG') 1579 >>> parser.add_argument('--foo', action='store_true', help='foo help') 1580 >>> subparsers = parser.add_subparsers(help='sub-command help') 1581 >>> 1582 >>> # create the parser for the "a" command 1583 >>> parser_a = subparsers.add_parser('a', help='a help') 1584 >>> parser_a.add_argument('bar', type=int, help='bar help') 1585 >>> 1586 >>> # create the parser for the "b" command 1587 >>> parser_b = subparsers.add_parser('b', help='b help') 1588 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help') 1589 >>> 1590 >>> # parse some argument lists 1591 >>> parser.parse_args(['a', '12']) 1592 Namespace(bar=12, foo=False) 1593 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z']) 1594 Namespace(baz='Z', foo=True) 1595 1596 Note that the object returned by :meth:`parse_args` will only contain 1597 attributes for the main parser and the subparser that was selected by the 1598 command line (and not any other subparsers). So in the example above, when 1599 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are 1600 present, and when the ``b`` command is specified, only the ``foo`` and 1601 ``baz`` attributes are present. 1602 1603 Similarly, when a help message is requested from a subparser, only the help 1604 for that particular parser will be printed. The help message will not 1605 include parent parser or sibling parser messages. (A help message for each 1606 subparser command, however, can be given by supplying the ``help=`` argument 1607 to :meth:`add_parser` as above.) 1608 1609 :: 1610 1611 >>> parser.parse_args(['--help']) 1612 usage: PROG [-h] [--foo] {a,b} ... 1613 1614 positional arguments: 1615 {a,b} sub-command help 1616 a a help 1617 b b help 1618 1619 optional arguments: 1620 -h, --help show this help message and exit 1621 --foo foo help 1622 1623 >>> parser.parse_args(['a', '--help']) 1624 usage: PROG a [-h] bar 1625 1626 positional arguments: 1627 bar bar help 1628 1629 optional arguments: 1630 -h, --help show this help message and exit 1631 1632 >>> parser.parse_args(['b', '--help']) 1633 usage: PROG b [-h] [--baz {X,Y,Z}] 1634 1635 optional arguments: 1636 -h, --help show this help message and exit 1637 --baz {X,Y,Z} baz help 1638 1639 The :meth:`add_subparsers` method also supports ``title`` and ``description`` 1640 keyword arguments. When either is present, the subparser's commands will 1641 appear in their own group in the help output. For example:: 1642 1643 >>> parser = argparse.ArgumentParser() 1644 >>> subparsers = parser.add_subparsers(title='subcommands', 1645 ... description='valid subcommands', 1646 ... help='additional help') 1647 >>> subparsers.add_parser('foo') 1648 >>> subparsers.add_parser('bar') 1649 >>> parser.parse_args(['-h']) 1650 usage: [-h] {foo,bar} ... 1651 1652 optional arguments: 1653 -h, --help show this help message and exit 1654 1655 subcommands: 1656 valid subcommands 1657 1658 {foo,bar} additional help 1659 1660 Furthermore, ``add_parser`` supports an additional ``aliases`` argument, 1661 which allows multiple strings to refer to the same subparser. This example, 1662 like ``svn``, aliases ``co`` as a shorthand for ``checkout``:: 1663 1664 >>> parser = argparse.ArgumentParser() 1665 >>> subparsers = parser.add_subparsers() 1666 >>> checkout = subparsers.add_parser('checkout', aliases=['co']) 1667 >>> checkout.add_argument('foo') 1668 >>> parser.parse_args(['co', 'bar']) 1669 Namespace(foo='bar') 1670 1671 One particularly effective way of handling sub-commands is to combine the use 1672 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so 1673 that each subparser knows which Python function it should execute. For 1674 example:: 1675 1676 >>> # sub-command functions 1677 >>> def foo(args): 1678 ... print(args.x * args.y) 1679 ... 1680 >>> def bar(args): 1681 ... print('((%s))' % args.z) 1682 ... 1683 >>> # create the top-level parser 1684 >>> parser = argparse.ArgumentParser() 1685 >>> subparsers = parser.add_subparsers() 1686 >>> 1687 >>> # create the parser for the "foo" command 1688 >>> parser_foo = subparsers.add_parser('foo') 1689 >>> parser_foo.add_argument('-x', type=int, default=1) 1690 >>> parser_foo.add_argument('y', type=float) 1691 >>> parser_foo.set_defaults(func=foo) 1692 >>> 1693 >>> # create the parser for the "bar" command 1694 >>> parser_bar = subparsers.add_parser('bar') 1695 >>> parser_bar.add_argument('z') 1696 >>> parser_bar.set_defaults(func=bar) 1697 >>> 1698 >>> # parse the args and call whatever function was selected 1699 >>> args = parser.parse_args('foo 1 -x 2'.split()) 1700 >>> args.func(args) 1701 2.0 1702 >>> 1703 >>> # parse the args and call whatever function was selected 1704 >>> args = parser.parse_args('bar XYZYX'.split()) 1705 >>> args.func(args) 1706 ((XYZYX)) 1707 1708 This way, you can let :meth:`parse_args` do the job of calling the 1709 appropriate function after argument parsing is complete. Associating 1710 functions with actions like this is typically the easiest way to handle the 1711 different actions for each of your subparsers. However, if it is necessary 1712 to check the name of the subparser that was invoked, the ``dest`` keyword 1713 argument to the :meth:`add_subparsers` call will work:: 1714 1715 >>> parser = argparse.ArgumentParser() 1716 >>> subparsers = parser.add_subparsers(dest='subparser_name') 1717 >>> subparser1 = subparsers.add_parser('1') 1718 >>> subparser1.add_argument('-x') 1719 >>> subparser2 = subparsers.add_parser('2') 1720 >>> subparser2.add_argument('y') 1721 >>> parser.parse_args(['2', 'frobble']) 1722 Namespace(subparser_name='2', y='frobble') 1723 1724 1725FileType objects 1726^^^^^^^^^^^^^^^^ 1727 1728.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None) 1729 1730 The :class:`FileType` factory creates objects that can be passed to the type 1731 argument of :meth:`ArgumentParser.add_argument`. Arguments that have 1732 :class:`FileType` objects as their type will open command-line arguments as 1733 files with the requested modes, buffer sizes, encodings and error handling 1734 (see the :func:`open` function for more details):: 1735 1736 >>> parser = argparse.ArgumentParser() 1737 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0)) 1738 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8')) 1739 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt']) 1740 Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>) 1741 1742 FileType objects understand the pseudo-argument ``'-'`` and automatically 1743 convert this into ``sys.stdin`` for readable :class:`FileType` objects and 1744 ``sys.stdout`` for writable :class:`FileType` objects:: 1745 1746 >>> parser = argparse.ArgumentParser() 1747 >>> parser.add_argument('infile', type=argparse.FileType('r')) 1748 >>> parser.parse_args(['-']) 1749 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>) 1750 1751 .. versionadded:: 3.4 1752 The *encodings* and *errors* keyword arguments. 1753 1754 1755Argument groups 1756^^^^^^^^^^^^^^^ 1757 1758.. method:: ArgumentParser.add_argument_group(title=None, description=None) 1759 1760 By default, :class:`ArgumentParser` groups command-line arguments into 1761 "positional arguments" and "optional arguments" when displaying help 1762 messages. When there is a better conceptual grouping of arguments than this 1763 default one, appropriate groups can be created using the 1764 :meth:`add_argument_group` method:: 1765 1766 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) 1767 >>> group = parser.add_argument_group('group') 1768 >>> group.add_argument('--foo', help='foo help') 1769 >>> group.add_argument('bar', help='bar help') 1770 >>> parser.print_help() 1771 usage: PROG [--foo FOO] bar 1772 1773 group: 1774 bar bar help 1775 --foo FOO foo help 1776 1777 The :meth:`add_argument_group` method returns an argument group object which 1778 has an :meth:`~ArgumentParser.add_argument` method just like a regular 1779 :class:`ArgumentParser`. When an argument is added to the group, the parser 1780 treats it just like a normal argument, but displays the argument in a 1781 separate group for help messages. The :meth:`add_argument_group` method 1782 accepts *title* and *description* arguments which can be used to 1783 customize this display:: 1784 1785 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) 1786 >>> group1 = parser.add_argument_group('group1', 'group1 description') 1787 >>> group1.add_argument('foo', help='foo help') 1788 >>> group2 = parser.add_argument_group('group2', 'group2 description') 1789 >>> group2.add_argument('--bar', help='bar help') 1790 >>> parser.print_help() 1791 usage: PROG [--bar BAR] foo 1792 1793 group1: 1794 group1 description 1795 1796 foo foo help 1797 1798 group2: 1799 group2 description 1800 1801 --bar BAR bar help 1802 1803 Note that any arguments not in your user-defined groups will end up back 1804 in the usual "positional arguments" and "optional arguments" sections. 1805 1806 1807Mutual exclusion 1808^^^^^^^^^^^^^^^^ 1809 1810.. method:: ArgumentParser.add_mutually_exclusive_group(required=False) 1811 1812 Create a mutually exclusive group. :mod:`argparse` will make sure that only 1813 one of the arguments in the mutually exclusive group was present on the 1814 command line:: 1815 1816 >>> parser = argparse.ArgumentParser(prog='PROG') 1817 >>> group = parser.add_mutually_exclusive_group() 1818 >>> group.add_argument('--foo', action='store_true') 1819 >>> group.add_argument('--bar', action='store_false') 1820 >>> parser.parse_args(['--foo']) 1821 Namespace(bar=True, foo=True) 1822 >>> parser.parse_args(['--bar']) 1823 Namespace(bar=False, foo=False) 1824 >>> parser.parse_args(['--foo', '--bar']) 1825 usage: PROG [-h] [--foo | --bar] 1826 PROG: error: argument --bar: not allowed with argument --foo 1827 1828 The :meth:`add_mutually_exclusive_group` method also accepts a *required* 1829 argument, to indicate that at least one of the mutually exclusive arguments 1830 is required:: 1831 1832 >>> parser = argparse.ArgumentParser(prog='PROG') 1833 >>> group = parser.add_mutually_exclusive_group(required=True) 1834 >>> group.add_argument('--foo', action='store_true') 1835 >>> group.add_argument('--bar', action='store_false') 1836 >>> parser.parse_args([]) 1837 usage: PROG [-h] (--foo | --bar) 1838 PROG: error: one of the arguments --foo --bar is required 1839 1840 Note that currently mutually exclusive argument groups do not support the 1841 *title* and *description* arguments of 1842 :meth:`~ArgumentParser.add_argument_group`. 1843 1844 1845Parser defaults 1846^^^^^^^^^^^^^^^ 1847 1848.. method:: ArgumentParser.set_defaults(**kwargs) 1849 1850 Most of the time, the attributes of the object returned by :meth:`parse_args` 1851 will be fully determined by inspecting the command-line arguments and the argument 1852 actions. :meth:`set_defaults` allows some additional 1853 attributes that are determined without any inspection of the command line to 1854 be added:: 1855 1856 >>> parser = argparse.ArgumentParser() 1857 >>> parser.add_argument('foo', type=int) 1858 >>> parser.set_defaults(bar=42, baz='badger') 1859 >>> parser.parse_args(['736']) 1860 Namespace(bar=42, baz='badger', foo=736) 1861 1862 Note that parser-level defaults always override argument-level defaults:: 1863 1864 >>> parser = argparse.ArgumentParser() 1865 >>> parser.add_argument('--foo', default='bar') 1866 >>> parser.set_defaults(foo='spam') 1867 >>> parser.parse_args([]) 1868 Namespace(foo='spam') 1869 1870 Parser-level defaults can be particularly useful when working with multiple 1871 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an 1872 example of this type. 1873 1874.. method:: ArgumentParser.get_default(dest) 1875 1876 Get the default value for a namespace attribute, as set by either 1877 :meth:`~ArgumentParser.add_argument` or by 1878 :meth:`~ArgumentParser.set_defaults`:: 1879 1880 >>> parser = argparse.ArgumentParser() 1881 >>> parser.add_argument('--foo', default='badger') 1882 >>> parser.get_default('foo') 1883 'badger' 1884 1885 1886Printing help 1887^^^^^^^^^^^^^ 1888 1889In most typical applications, :meth:`~ArgumentParser.parse_args` will take 1890care of formatting and printing any usage or error messages. However, several 1891formatting methods are available: 1892 1893.. method:: ArgumentParser.print_usage(file=None) 1894 1895 Print a brief description of how the :class:`ArgumentParser` should be 1896 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is 1897 assumed. 1898 1899.. method:: ArgumentParser.print_help(file=None) 1900 1901 Print a help message, including the program usage and information about the 1902 arguments registered with the :class:`ArgumentParser`. If *file* is 1903 ``None``, :data:`sys.stdout` is assumed. 1904 1905There are also variants of these methods that simply return a string instead of 1906printing it: 1907 1908.. method:: ArgumentParser.format_usage() 1909 1910 Return a string containing a brief description of how the 1911 :class:`ArgumentParser` should be invoked on the command line. 1912 1913.. method:: ArgumentParser.format_help() 1914 1915 Return a string containing a help message, including the program usage and 1916 information about the arguments registered with the :class:`ArgumentParser`. 1917 1918 1919Partial parsing 1920^^^^^^^^^^^^^^^ 1921 1922.. method:: ArgumentParser.parse_known_args(args=None, namespace=None) 1923 1924Sometimes a script may only parse a few of the command-line arguments, passing 1925the remaining arguments on to another script or program. In these cases, the 1926:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like 1927:meth:`~ArgumentParser.parse_args` except that it does not produce an error when 1928extra arguments are present. Instead, it returns a two item tuple containing 1929the populated namespace and the list of remaining argument strings. 1930 1931:: 1932 1933 >>> parser = argparse.ArgumentParser() 1934 >>> parser.add_argument('--foo', action='store_true') 1935 >>> parser.add_argument('bar') 1936 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam']) 1937 (Namespace(bar='BAR', foo=True), ['--badger', 'spam']) 1938 1939.. warning:: 1940 :ref:`Prefix matching <prefix-matching>` rules apply to 1941 :meth:`parse_known_args`. The parser may consume an option even if it's just 1942 a prefix of one of its known options, instead of leaving it in the remaining 1943 arguments list. 1944 1945 1946Customizing file parsing 1947^^^^^^^^^^^^^^^^^^^^^^^^ 1948 1949.. method:: ArgumentParser.convert_arg_line_to_args(arg_line) 1950 1951 Arguments that are read from a file (see the *fromfile_prefix_chars* 1952 keyword argument to the :class:`ArgumentParser` constructor) are read one 1953 argument per line. :meth:`convert_arg_line_to_args` can be overridden for 1954 fancier reading. 1955 1956 This method takes a single argument *arg_line* which is a string read from 1957 the argument file. It returns a list of arguments parsed from this string. 1958 The method is called once per line read from the argument file, in order. 1959 1960 A useful override of this method is one that treats each space-separated word 1961 as an argument. The following example demonstrates how to do this:: 1962 1963 class MyArgumentParser(argparse.ArgumentParser): 1964 def convert_arg_line_to_args(self, arg_line): 1965 return arg_line.split() 1966 1967 1968Exiting methods 1969^^^^^^^^^^^^^^^ 1970 1971.. method:: ArgumentParser.exit(status=0, message=None) 1972 1973 This method terminates the program, exiting with the specified *status* 1974 and, if given, it prints a *message* before that. 1975 1976.. method:: ArgumentParser.error(message) 1977 1978 This method prints a usage message including the *message* to the 1979 standard error and terminates the program with a status code of 2. 1980 1981.. _upgrading-optparse-code: 1982 1983Upgrading optparse code 1984----------------------- 1985 1986Originally, the :mod:`argparse` module had attempted to maintain compatibility 1987with :mod:`optparse`. However, :mod:`optparse` was difficult to extend 1988transparently, particularly with the changes required to support the new 1989``nargs=`` specifiers and better usage messages. When most everything in 1990:mod:`optparse` had either been copy-pasted over or monkey-patched, it no 1991longer seemed practical to try to maintain the backwards compatibility. 1992 1993The :mod:`argparse` module improves on the standard library :mod:`optparse` 1994module in a number of ways including: 1995 1996* Handling positional arguments. 1997* Supporting sub-commands. 1998* Allowing alternative option prefixes like ``+`` and ``/``. 1999* Handling zero-or-more and one-or-more style arguments. 2000* Producing more informative usage messages. 2001* Providing a much simpler interface for custom ``type`` and ``action``. 2002 2003A partial upgrade path from :mod:`optparse` to :mod:`argparse`: 2004 2005* Replace all :meth:`optparse.OptionParser.add_option` calls with 2006 :meth:`ArgumentParser.add_argument` calls. 2007 2008* Replace ``(options, args) = parser.parse_args()`` with ``args = 2009 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` 2010 calls for the positional arguments. Keep in mind that what was previously 2011 called ``options``, now in :mod:`argparse` context is called ``args``. 2012 2013* Replace callback actions and the ``callback_*`` keyword arguments with 2014 ``type`` or ``action`` arguments. 2015 2016* Replace string names for ``type`` keyword arguments with the corresponding 2017 type objects (e.g. int, float, complex, etc). 2018 2019* Replace :class:`optparse.Values` with :class:`Namespace` and 2020 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with 2021 :exc:`ArgumentError`. 2022 2023* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with 2024 the standard Python syntax to use dictionaries to format strings, that is, 2025 ``%(default)s`` and ``%(prog)s``. 2026 2027* Replace the OptionParser constructor ``version`` argument with a call to 2028 ``parser.add_argument('--version', action='version', version='<the version>')``. 2029