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