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