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