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