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