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