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