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