Debian Codegraph @

Doc/library/argparse.rst

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