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