blob: d853d2afbe372fcb5d1621d02182c327effe2864 [file] [log] [blame]
Georg Brandl69518bc2011-04-16 16:44:54 +02001:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
Georg Brandle0bf91d2010-10-17 10:34:28 +00002===============================================================================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4.. module:: argparse
Éric Araujod9d7bca2011-08-10 04:19:03 +02005 :synopsis: Command-line option and argument parsing library.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Benjamin Peterson698a18a2010-03-02 22:34:37 +00007.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
Benjamin Peterson698a18a2010-03-02 22:34:37 +00008.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
9
Raymond Hettingera1993682011-01-27 01:20:32 +000010.. versionadded:: 3.2
11
Éric Araujo19f9b712011-08-19 00:49:18 +020012**Source code:** :source:`Lib/argparse.py`
13
Raymond Hettingera1993682011-01-27 01:20:32 +000014--------------
Benjamin Peterson698a18a2010-03-02 22:34:37 +000015
Ezio Melotti6cc7a412012-05-06 16:15:35 +030016.. sidebar:: Tutorial
17
18 This page contains the API reference information. For a more gentle
19 introduction to Python command-line parsing, have a look at the
20 :ref:`argparse tutorial <argparse-tutorial>`.
21
Ezio Melotti2409d772011-04-16 23:13:50 +030022The :mod:`argparse` module makes it easy to write user-friendly command-line
Benjamin Peterson98047eb2010-03-03 02:07:08 +000023interfaces. The program defines what arguments it requires, and :mod:`argparse`
Benjamin Peterson698a18a2010-03-02 22:34:37 +000024will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson98047eb2010-03-03 02:07:08 +000025module also automatically generates help and usage messages and issues errors
26when users give the program invalid arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000027
Georg Brandle0bf91d2010-10-17 10:34:28 +000028
Benjamin Peterson698a18a2010-03-02 22:34:37 +000029Example
30-------
31
Benjamin Peterson98047eb2010-03-03 02:07:08 +000032The following code is a Python program that takes a list of integers and
33produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000034
35 import argparse
36
37 parser = argparse.ArgumentParser(description='Process some integers.')
38 parser.add_argument('integers', metavar='N', type=int, nargs='+',
Serhiy Storchakadba90392016-05-10 12:01:23 +030039 help='an integer for the accumulator')
Benjamin Peterson698a18a2010-03-02 22:34:37 +000040 parser.add_argument('--sum', dest='accumulate', action='store_const',
Serhiy Storchakadba90392016-05-10 12:01:23 +030041 const=sum, default=max,
42 help='sum the integers (default: find the max)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +000043
44 args = parser.parse_args()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000045 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000046
47Assuming the Python code above is saved into a file called ``prog.py``, it can
Martin Panter1050d2d2016-07-26 11:18:21 +020048be run at the command line and provides useful help messages:
49
50.. code-block:: shell-session
Benjamin Peterson698a18a2010-03-02 22:34:37 +000051
Georg Brandl29fc4bf2013-10-06 19:33:56 +020052 $ python prog.py -h
Benjamin Peterson698a18a2010-03-02 22:34:37 +000053 usage: prog.py [-h] [--sum] N [N ...]
54
55 Process some integers.
56
57 positional arguments:
58 N an integer for the accumulator
59
Raymond Hettinger41b223d2020-12-23 09:40:56 -080060 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +000061 -h, --help show this help message and exit
62 --sum sum the integers (default: find the max)
63
64When run with the appropriate arguments, it prints either the sum or the max of
Martin Panter1050d2d2016-07-26 11:18:21 +020065the command-line integers:
66
67.. code-block:: shell-session
Benjamin Peterson698a18a2010-03-02 22:34:37 +000068
Georg Brandl29fc4bf2013-10-06 19:33:56 +020069 $ python prog.py 1 2 3 4
Benjamin Peterson698a18a2010-03-02 22:34:37 +000070 4
71
Georg Brandl29fc4bf2013-10-06 19:33:56 +020072 $ python prog.py 1 2 3 4 --sum
Benjamin Peterson698a18a2010-03-02 22:34:37 +000073 10
74
Martin Panter1050d2d2016-07-26 11:18:21 +020075If invalid arguments are passed in, it will issue an error:
76
77.. code-block:: shell-session
Benjamin Peterson698a18a2010-03-02 22:34:37 +000078
Georg Brandl29fc4bf2013-10-06 19:33:56 +020079 $ python prog.py a b c
Benjamin Peterson698a18a2010-03-02 22:34:37 +000080 usage: prog.py [-h] [--sum] N [N ...]
81 prog.py: error: argument N: invalid int value: 'a'
82
83The following sections walk you through this example.
84
Georg Brandle0bf91d2010-10-17 10:34:28 +000085
Benjamin Peterson698a18a2010-03-02 22:34:37 +000086Creating a parser
87^^^^^^^^^^^^^^^^^
88
Benjamin Peterson2614cda2010-03-21 22:36:19 +000089The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000090:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000091
92 >>> parser = argparse.ArgumentParser(description='Process some integers.')
93
94The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotticca4ef82011-04-21 15:26:46 +030095parse the command line into Python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000096
97
98Adding arguments
99^^^^^^^^^^^^^^^^
100
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000101Filling an :class:`ArgumentParser` with information about program arguments is
102done by making calls to the :meth:`~ArgumentParser.add_argument` method.
103Generally, these calls tell the :class:`ArgumentParser` how to take the strings
104on the command line and turn them into objects. This information is stored and
105used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000106
107 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
108 ... help='an integer for the accumulator')
109 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
110 ... const=sum, default=max,
111 ... help='sum the integers (default: find the max)')
112
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300113Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000114two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
115will be a list of one or more ints, and the ``accumulate`` attribute will be
116either the :func:`sum` function, if ``--sum`` was specified at the command line,
117or the :func:`max` function if it was not.
118
Georg Brandle0bf91d2010-10-17 10:34:28 +0000119
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000120Parsing arguments
121^^^^^^^^^^^^^^^^^
122
Éric Araujod9d7bca2011-08-10 04:19:03 +0200123:class:`ArgumentParser` parses arguments through the
Georg Brandl69518bc2011-04-16 16:44:54 +0200124:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujofde92422011-08-19 01:30:26 +0200125convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujo63b18a42011-07-29 17:59:17 +0200126In most cases, this means a simple :class:`Namespace` object will be built up from
Georg Brandl69518bc2011-04-16 16:44:54 +0200127attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000128
129 >>> parser.parse_args(['--sum', '7', '-1', '42'])
130 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
131
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000132In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
133arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujod9d7bca2011-08-10 04:19:03 +0200134command-line arguments from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000135
136
137ArgumentParser objects
138----------------------
139
Ezio Melottie0add762012-09-14 06:32:35 +0300140.. class:: ArgumentParser(prog=None, usage=None, description=None, \
141 epilog=None, parents=[], \
142 formatter_class=argparse.HelpFormatter, \
143 prefix_chars='-', fromfile_prefix_chars=None, \
144 argument_default=None, conflict_handler='error', \
Hai Shif5456382019-09-12 05:56:05 -0500145 add_help=True, allow_abbrev=True, exit_on_error=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000146
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300147 Create a new :class:`ArgumentParser` object. All parameters should be passed
148 as keyword arguments. Each parameter has its own more detailed description
149 below, but in short they are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000150
Miss Islington (bot)74af7132022-01-02 13:29:35 -0800151 * prog_ - The name of the program (default:
152 ``os.path.basename(sys.argv[0])``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000153
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300154 * usage_ - The string describing the program usage (default: generated from
155 arguments added to parser)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000156
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300157 * description_ - Text to display before the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000158
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300159 * epilog_ - Text to display after the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000160
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000161 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300162 also be included
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000163
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300164 * formatter_class_ - A class for customizing the help output
165
166 * prefix_chars_ - The set of characters that prefix optional arguments
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000167 (default: '-')
168
169 * fromfile_prefix_chars_ - The set of characters that prefix files from
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300170 which additional arguments should be read (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000171
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300172 * argument_default_ - The global default value for arguments
173 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000174
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300175 * conflict_handler_ - The strategy for resolving conflicting optionals
176 (usually unnecessary)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000177
Martin Panter536d70e2017-01-14 08:23:08 +0000178 * add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000179
Berker Peksag8089cd62015-02-14 01:39:17 +0200180 * allow_abbrev_ - Allows long options to be abbreviated if the
181 abbreviation is unambiguous. (default: ``True``)
182
Hai Shif5456382019-09-12 05:56:05 -0500183 * exit_on_error_ - Determines whether or not ArgumentParser exits with
184 error info when an error occurs. (default: ``True``)
185
Berker Peksag8089cd62015-02-14 01:39:17 +0200186 .. versionchanged:: 3.5
187 *allow_abbrev* parameter was added.
188
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500189 .. versionchanged:: 3.8
190 In previous versions, *allow_abbrev* also disabled grouping of short
191 flags such as ``-vv`` to mean ``-v -v``.
192
Hai Shif5456382019-09-12 05:56:05 -0500193 .. versionchanged:: 3.9
194 *exit_on_error* parameter was added.
195
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000196The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000197
198
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300199prog
200^^^^
201
Martin Panter0f0eac42016-09-07 11:04:41 +0000202By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300203how to display the name of the program in help messages. This default is almost
204always desirable because it will make the help messages match how the program was
205invoked on the command line. For example, consider a file named
206``myprogram.py`` with the following code::
207
208 import argparse
209 parser = argparse.ArgumentParser()
210 parser.add_argument('--foo', help='foo help')
211 args = parser.parse_args()
212
213The help for this program will display ``myprogram.py`` as the program name
Martin Panter1050d2d2016-07-26 11:18:21 +0200214(regardless of where the program was invoked from):
215
216.. code-block:: shell-session
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300217
218 $ python myprogram.py --help
219 usage: myprogram.py [-h] [--foo FOO]
220
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800221 options:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300222 -h, --help show this help message and exit
223 --foo FOO foo help
224 $ cd ..
Martin Panter536d70e2017-01-14 08:23:08 +0000225 $ python subdir/myprogram.py --help
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300226 usage: myprogram.py [-h] [--foo FOO]
227
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800228 options:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300229 -h, --help show this help message and exit
230 --foo FOO foo help
231
232To change this default behavior, another value can be supplied using the
233``prog=`` argument to :class:`ArgumentParser`::
234
235 >>> parser = argparse.ArgumentParser(prog='myprogram')
236 >>> parser.print_help()
237 usage: myprogram [-h]
238
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800239 options:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300240 -h, --help show this help message and exit
241
242Note that the program name, whether determined from ``sys.argv[0]`` or from the
243``prog=`` argument, is available to help messages using the ``%(prog)s`` format
244specifier.
245
246::
247
248 >>> parser = argparse.ArgumentParser(prog='myprogram')
249 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
250 >>> parser.print_help()
251 usage: myprogram [-h] [--foo FOO]
252
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800253 options:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300254 -h, --help show this help message and exit
255 --foo FOO foo of the myprogram program
256
257
258usage
259^^^^^
260
261By default, :class:`ArgumentParser` calculates the usage message from the
262arguments it contains::
263
264 >>> parser = argparse.ArgumentParser(prog='PROG')
265 >>> parser.add_argument('--foo', nargs='?', help='foo help')
266 >>> parser.add_argument('bar', nargs='+', help='bar help')
267 >>> parser.print_help()
268 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
269
270 positional arguments:
271 bar bar help
272
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800273 options:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300274 -h, --help show this help message and exit
275 --foo [FOO] foo help
276
277The default message can be overridden with the ``usage=`` keyword argument::
278
279 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
280 >>> parser.add_argument('--foo', nargs='?', help='foo help')
281 >>> parser.add_argument('bar', nargs='+', help='bar help')
282 >>> parser.print_help()
283 usage: PROG [options]
284
285 positional arguments:
286 bar bar help
287
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800288 options:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300289 -h, --help show this help message and exit
290 --foo [FOO] foo help
291
292The ``%(prog)s`` format specifier is available to fill in the program name in
293your usage messages.
294
295
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000296description
297^^^^^^^^^^^
298
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000299Most calls to the :class:`ArgumentParser` constructor will use the
300``description=`` keyword argument. This argument gives a brief description of
301what the program does and how it works. In help messages, the description is
302displayed between the command-line usage string and the help messages for the
303various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000304
305 >>> parser = argparse.ArgumentParser(description='A foo that bars')
306 >>> parser.print_help()
307 usage: argparse.py [-h]
308
309 A foo that bars
310
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800311 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000312 -h, --help show this help message and exit
313
314By default, the description will be line-wrapped so that it fits within the
315given space. To change this behavior, see the formatter_class_ argument.
316
317
318epilog
319^^^^^^
320
321Some programs like to display additional description of the program after the
322description of the arguments. Such text can be specified using the ``epilog=``
323argument to :class:`ArgumentParser`::
324
325 >>> parser = argparse.ArgumentParser(
326 ... description='A foo that bars',
327 ... epilog="And that's how you'd foo a bar")
328 >>> parser.print_help()
329 usage: argparse.py [-h]
330
331 A foo that bars
332
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800333 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000334 -h, --help show this help message and exit
335
336 And that's how you'd foo a bar
337
338As with the description_ argument, the ``epilog=`` text is by default
339line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000340argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000341
342
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000343parents
344^^^^^^^
345
346Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000347repeating the definitions of these arguments, a single parser with all the
348shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
349can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
350objects, collects all the positional and optional actions from them, and adds
351these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000352
353 >>> parent_parser = argparse.ArgumentParser(add_help=False)
354 >>> parent_parser.add_argument('--parent', type=int)
355
356 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
357 >>> foo_parser.add_argument('foo')
358 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
359 Namespace(foo='XXX', parent=2)
360
361 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
362 >>> bar_parser.add_argument('--bar')
363 >>> bar_parser.parse_args(['--bar', 'YYY'])
364 Namespace(bar='YYY', parent=None)
365
366Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000367:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
368and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000369
Steven Bethardd186f992011-03-26 21:49:00 +0100370.. note::
371 You must fully initialize the parsers before passing them via ``parents=``.
372 If you change the parent parsers after the child parser, those changes will
373 not be reflected in the child.
374
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000375
376formatter_class
377^^^^^^^^^^^^^^^
378
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000379:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300380specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300381classes:
382
383.. class:: RawDescriptionHelpFormatter
384 RawTextHelpFormatter
385 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300386 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000387
Steven Bethard0331e902011-03-26 14:48:04 +0100388:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
389more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000390By default, :class:`ArgumentParser` objects line-wrap the description_ and
391epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000392
393 >>> parser = argparse.ArgumentParser(
394 ... prog='PROG',
395 ... description='''this description
396 ... was indented weird
397 ... but that is okay''',
398 ... epilog='''
399 ... likewise for this epilog whose whitespace will
400 ... be cleaned up and whose words will be wrapped
401 ... across a couple lines''')
402 >>> parser.print_help()
403 usage: PROG [-h]
404
405 this description was indented weird but that is okay
406
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800407 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000408 -h, --help show this help message and exit
409
410 likewise for this epilog whose whitespace will be cleaned up and whose words
411 will be wrapped across a couple lines
412
Steven Bethard0331e902011-03-26 14:48:04 +0100413Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000414indicates that description_ and epilog_ are already correctly formatted and
415should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000416
417 >>> parser = argparse.ArgumentParser(
418 ... prog='PROG',
419 ... formatter_class=argparse.RawDescriptionHelpFormatter,
420 ... description=textwrap.dedent('''\
421 ... Please do not mess up this text!
422 ... --------------------------------
423 ... I have indented it
424 ... exactly the way
425 ... I want it
426 ... '''))
427 >>> parser.print_help()
428 usage: PROG [-h]
429
430 Please do not mess up this text!
431 --------------------------------
432 I have indented it
433 exactly the way
434 I want it
435
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800436 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000437 -h, --help show this help message and exit
438
Steven Bethard0331e902011-03-26 14:48:04 +0100439:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Elena Oat397c4672017-09-07 23:06:45 +0300440including argument descriptions. However, multiple new lines are replaced with
441one. If you wish to preserve multiple blank lines, add spaces between the
442newlines.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000443
Steven Bethard0331e902011-03-26 14:48:04 +0100444:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
445default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000446
447 >>> parser = argparse.ArgumentParser(
448 ... prog='PROG',
449 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
450 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
451 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
452 >>> parser.print_help()
Brandt Buchera0ed99b2019-11-11 12:47:48 -0800453 usage: PROG [-h] [--foo FOO] [bar ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000454
455 positional arguments:
456 bar BAR! (default: [1, 2, 3])
457
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800458 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000459 -h, --help show this help message and exit
460 --foo FOO FOO! (default: 42)
461
Steven Bethard0331e902011-03-26 14:48:04 +0100462:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300463argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100464as the regular formatter does)::
465
466 >>> parser = argparse.ArgumentParser(
467 ... prog='PROG',
468 ... formatter_class=argparse.MetavarTypeHelpFormatter)
469 >>> parser.add_argument('--foo', type=int)
470 >>> parser.add_argument('bar', type=float)
471 >>> parser.print_help()
472 usage: PROG [-h] [--foo int] float
473
474 positional arguments:
475 float
476
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800477 options:
Steven Bethard0331e902011-03-26 14:48:04 +0100478 -h, --help show this help message and exit
479 --foo int
480
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000481
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300482prefix_chars
483^^^^^^^^^^^^
484
485Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
486Parsers that need to support different or additional prefix
487characters, e.g. for options
488like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
489to the ArgumentParser constructor::
490
491 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
492 >>> parser.add_argument('+f')
493 >>> parser.add_argument('++bar')
494 >>> parser.parse_args('+f X ++bar Y'.split())
495 Namespace(bar='Y', f='X')
496
497The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
498characters that does not include ``-`` will cause ``-f/--foo`` options to be
499disallowed.
500
501
502fromfile_prefix_chars
503^^^^^^^^^^^^^^^^^^^^^
504
505Sometimes, for example when dealing with a particularly long argument lists, it
506may make sense to keep the list of arguments in a file rather than typing it out
507at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
508:class:`ArgumentParser` constructor, then arguments that start with any of the
509specified characters will be treated as files, and will be replaced by the
510arguments they contain. For example::
511
512 >>> with open('args.txt', 'w') as fp:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300513 ... fp.write('-f\nbar')
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300514 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
515 >>> parser.add_argument('-f')
516 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
517 Namespace(f='bar')
518
519Arguments read from a file must by default be one per line (but see also
520:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
521were in the same place as the original file referencing argument on the command
522line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
523is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
524
525The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
526arguments will never be treated as file references.
527
528
529argument_default
530^^^^^^^^^^^^^^^^
531
532Generally, argument defaults are specified either by passing a default to
533:meth:`~ArgumentParser.add_argument` or by calling the
534:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
535pairs. Sometimes however, it may be useful to specify a single parser-wide
536default for arguments. This can be accomplished by passing the
537``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
538to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
539calls, we supply ``argument_default=SUPPRESS``::
540
541 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
542 >>> parser.add_argument('--foo')
543 >>> parser.add_argument('bar', nargs='?')
544 >>> parser.parse_args(['--foo', '1', 'BAR'])
545 Namespace(bar='BAR', foo='1')
546 >>> parser.parse_args([])
547 Namespace()
548
Berker Peksag8089cd62015-02-14 01:39:17 +0200549.. _allow_abbrev:
550
551allow_abbrev
552^^^^^^^^^^^^
553
554Normally, when you pass an argument list to the
Martin Panterd2ad5712015-11-02 04:20:33 +0000555:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`,
Berker Peksag8089cd62015-02-14 01:39:17 +0200556it :ref:`recognizes abbreviations <prefix-matching>` of long options.
557
558This feature can be disabled by setting ``allow_abbrev`` to ``False``::
559
560 >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
561 >>> parser.add_argument('--foobar', action='store_true')
562 >>> parser.add_argument('--foonley', action='store_false')
Berker Peksage7e497b2015-03-12 20:47:41 +0200563 >>> parser.parse_args(['--foon'])
Berker Peksag8089cd62015-02-14 01:39:17 +0200564 usage: PROG [-h] [--foobar] [--foonley]
565 PROG: error: unrecognized arguments: --foon
566
567.. versionadded:: 3.5
568
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300569
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000570conflict_handler
571^^^^^^^^^^^^^^^^
572
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000573:class:`ArgumentParser` objects do not allow two actions with the same option
Martin Panter0f0eac42016-09-07 11:04:41 +0000574string. By default, :class:`ArgumentParser` objects raise an exception if an
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000575attempt is made to create an argument with an option string that is already in
576use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000577
578 >>> parser = argparse.ArgumentParser(prog='PROG')
579 >>> parser.add_argument('-f', '--foo', help='old foo help')
580 >>> parser.add_argument('--foo', help='new foo help')
581 Traceback (most recent call last):
582 ..
583 ArgumentError: argument --foo: conflicting option string(s): --foo
584
585Sometimes (e.g. when using parents_) it may be useful to simply override any
586older arguments with the same option string. To get this behavior, the value
587``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000588:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000589
590 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
591 >>> parser.add_argument('-f', '--foo', help='old foo help')
592 >>> parser.add_argument('--foo', help='new foo help')
593 >>> parser.print_help()
594 usage: PROG [-h] [-f FOO] [--foo FOO]
595
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800596 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000597 -h, --help show this help message and exit
598 -f FOO old foo help
599 --foo FOO new foo help
600
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000601Note that :class:`ArgumentParser` objects only remove an action if all of its
602option strings are overridden. So, in the example above, the old ``-f/--foo``
603action is retained as the ``-f`` action, because only the ``--foo`` option
604string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000605
606
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300607add_help
608^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000609
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300610By default, ArgumentParser objects add an option which simply displays
611the parser's help message. For example, consider a file named
612``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000613
614 import argparse
615 parser = argparse.ArgumentParser()
616 parser.add_argument('--foo', help='foo help')
617 args = parser.parse_args()
618
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300619If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Martin Panter1050d2d2016-07-26 11:18:21 +0200620help will be printed:
621
622.. code-block:: shell-session
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000623
624 $ python myprogram.py --help
625 usage: myprogram.py [-h] [--foo FOO]
626
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800627 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000628 -h, --help show this help message and exit
629 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000630
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300631Occasionally, it may be useful to disable the addition of this help option.
632This can be achieved by passing ``False`` as the ``add_help=`` argument to
633:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000634
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300635 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
636 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000637 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300638 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000639
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800640 options:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300641 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000642
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300643The help option is typically ``-h/--help``. The exception to this is
644if the ``prefix_chars=`` is specified and does not include ``-``, in
645which case ``-h`` and ``--help`` are not valid options. In
646this case, the first character in ``prefix_chars`` is used to prefix
647the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000648
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300649 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000650 >>> parser.print_help()
Georg Brandld2914ce2013-10-06 09:50:36 +0200651 usage: PROG [+h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000652
Raymond Hettinger41b223d2020-12-23 09:40:56 -0800653 options:
Georg Brandld2914ce2013-10-06 09:50:36 +0200654 +h, ++help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000655
656
Hai Shif5456382019-09-12 05:56:05 -0500657exit_on_error
658^^^^^^^^^^^^^
659
660Normally, when you pass an invalid argument list to the :meth:`~ArgumentParser.parse_args`
661method of an :class:`ArgumentParser`, it will exit with error info.
662
Taneli Hukkinen7be870f2021-04-26 06:04:26 +0200663If the user would like to catch errors manually, the feature can be enabled by setting
Hai Shif5456382019-09-12 05:56:05 -0500664``exit_on_error`` to ``False``::
665
666 >>> parser = argparse.ArgumentParser(exit_on_error=False)
667 >>> parser.add_argument('--integers', type=int)
668 _StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)
669 >>> try:
670 ... parser.parse_args('--integers a'.split())
671 ... except argparse.ArgumentError:
672 ... print('Catching an argumentError')
673 ...
674 Catching an argumentError
675
676.. versionadded:: 3.9
677
678
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000679The add_argument() method
680-------------------------
681
Georg Brandlc9007082011-01-09 09:04:08 +0000682.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
683 [const], [default], [type], [choices], [required], \
684 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000685
Georg Brandl69518bc2011-04-16 16:44:54 +0200686 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000687 has its own more detailed description below, but in short they are:
688
689 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300690 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000691
692 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200693 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000694
695 * nargs_ - The number of command-line arguments that should be consumed.
696
697 * const_ - A constant value required by some action_ and nargs_ selections.
698
699 * default_ - The value produced if the argument is absent from the
Raymond Hettinger752cdf22020-12-06 18:29:08 -0800700 command line and if it is absent from the namespace object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000701
Ezio Melotti2409d772011-04-16 23:13:50 +0300702 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000703
704 * choices_ - A container of the allowable values for the argument.
705
706 * required_ - Whether or not the command-line option may be omitted
707 (optionals only).
708
709 * help_ - A brief description of what the argument does.
710
711 * metavar_ - A name for the argument in usage messages.
712
713 * dest_ - The name of the attribute to be added to the object returned by
714 :meth:`parse_args`.
715
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000716The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000717
Georg Brandle0bf91d2010-10-17 10:34:28 +0000718
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000719name or flags
720^^^^^^^^^^^^^
721
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300722The :meth:`~ArgumentParser.add_argument` method must know whether an optional
723argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
724filenames, is expected. The first arguments passed to
725:meth:`~ArgumentParser.add_argument` must therefore be either a series of
726flags, or a simple argument name. For example, an optional argument could
727be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000728
729 >>> parser.add_argument('-f', '--foo')
730
731while a positional argument could be created like::
732
733 >>> parser.add_argument('bar')
734
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300735When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
736identified by the ``-`` prefix, and the remaining arguments will be assumed to
737be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000738
739 >>> parser = argparse.ArgumentParser(prog='PROG')
740 >>> parser.add_argument('-f', '--foo')
741 >>> parser.add_argument('bar')
742 >>> parser.parse_args(['BAR'])
743 Namespace(bar='BAR', foo=None)
744 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
745 Namespace(bar='BAR', foo='FOO')
746 >>> parser.parse_args(['--foo', 'FOO'])
747 usage: PROG [-h] [-f FOO] bar
suic8604e82932018-04-11 20:45:04 +0200748 PROG: error: the following arguments are required: bar
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000749
Georg Brandle0bf91d2010-10-17 10:34:28 +0000750
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000751action
752^^^^^^
753
Éric Araujod9d7bca2011-08-10 04:19:03 +0200754:class:`ArgumentParser` objects associate command-line arguments with actions. These
755actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000756them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300757:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -0500758how the command-line arguments should be handled. The supplied actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000759
760* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300761 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000762
763 >>> parser = argparse.ArgumentParser()
764 >>> parser.add_argument('--foo')
765 >>> parser.parse_args('--foo 1'.split())
766 Namespace(foo='1')
767
768* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panterb4912b82016-04-09 03:49:48 +0000769 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300770 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000771
772 >>> parser = argparse.ArgumentParser()
773 >>> parser.add_argument('--foo', action='store_const', const=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000774 >>> parser.parse_args(['--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000775 Namespace(foo=42)
776
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800777* ``'store_true'`` and ``'store_false'`` - These are special cases of
778 ``'store_const'`` used for storing the values ``True`` and ``False``
779 respectively. In addition, they create default values of ``False`` and
780 ``True`` respectively. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000781
782 >>> parser = argparse.ArgumentParser()
783 >>> parser.add_argument('--foo', action='store_true')
784 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800785 >>> parser.add_argument('--baz', action='store_false')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000786 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800787 Namespace(foo=True, bar=False, baz=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000788
789* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000790 list. This is useful to allow an option to be specified multiple times.
791 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000792
793 >>> parser = argparse.ArgumentParser()
794 >>> parser.add_argument('--foo', action='append')
795 >>> parser.parse_args('--foo 1 --foo 2'.split())
796 Namespace(foo=['1', '2'])
797
798* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000799 the const_ keyword argument to the list. (Note that the const_ keyword
800 argument defaults to ``None``.) The ``'append_const'`` action is typically
801 useful when multiple arguments need to store constants to the same list. For
802 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000803
804 >>> parser = argparse.ArgumentParser()
805 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
806 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
807 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200808 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000809
Sandro Tosi98492a52012-01-04 23:25:04 +0100810* ``'count'`` - This counts the number of times a keyword argument occurs. For
811 example, this is useful for increasing verbosity levels::
812
813 >>> parser = argparse.ArgumentParser()
Raymond Hettinger04c79d62019-11-17 22:06:19 -0800814 >>> parser.add_argument('--verbose', '-v', action='count', default=0)
Martin Panterf5e60482016-04-26 11:41:25 +0000815 >>> parser.parse_args(['-vvv'])
Sandro Tosi98492a52012-01-04 23:25:04 +0100816 Namespace(verbose=3)
817
Raymond Hettinger04c79d62019-11-17 22:06:19 -0800818 Note, the *default* will be ``None`` unless explicitly set to *0*.
819
Sandro Tosi98492a52012-01-04 23:25:04 +0100820* ``'help'`` - This prints a complete help message for all the options in the
821 current parser and then exits. By default a help action is automatically
822 added to the parser. See :class:`ArgumentParser` for details of how the
823 output is created.
824
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000825* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300826 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100827 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000828
829 >>> import argparse
830 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000831 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
832 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000833 PROG 2.0
834
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +0300835* ``'extend'`` - This stores a list, and extends each argument value to the
836 list.
837 Example usage::
838
839 >>> parser = argparse.ArgumentParser()
840 >>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
841 >>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
842 Namespace(foo=['f1', 'f2', 'f3', 'f4'])
843
Batuhan Taşkaya74142072019-10-20 23:13:54 +0300844 .. versionadded:: 3.8
845
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400846You may also specify an arbitrary action by passing an Action subclass or
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200847other object that implements the same interface. The ``BooleanOptionalAction``
848is available in ``argparse`` and adds support for boolean actions such as
849``--foo`` and ``--no-foo``::
850
851 >>> import argparse
852 >>> parser = argparse.ArgumentParser()
853 >>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
854 >>> parser.parse_args(['--no-foo'])
855 Namespace(foo=False)
856
Miss Islington (bot)721d4792021-07-12 08:43:16 -0700857.. versionadded:: 3.9
858
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200859The recommended way to create a custom action is to extend :class:`Action`,
860overriding the ``__call__`` method and optionally the ``__init__`` and
861``format_usage`` methods.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000862
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000863An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000864
865 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400866 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
867 ... if nargs is not None:
868 ... raise ValueError("nargs not allowed")
Andre Delfino52cd6d52021-04-26 19:13:54 -0300869 ... super().__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000870 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000871 ... print('%r %r %r' % (namespace, values, option_string))
872 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000873 ...
874 >>> parser = argparse.ArgumentParser()
875 >>> parser.add_argument('--foo', action=FooAction)
876 >>> parser.add_argument('bar', action=FooAction)
877 >>> args = parser.parse_args('1 --foo 2'.split())
878 Namespace(bar=None, foo=None) '1' None
879 Namespace(bar='1', foo=None) '2' '--foo'
880 >>> args
881 Namespace(bar='1', foo='2')
882
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400883For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000884
885nargs
886^^^^^
887
888ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000889single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300890different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000891values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000892
Éric Araujoc3ef0372012-02-20 01:44:55 +0100893* ``N`` (an integer). ``N`` arguments from the command line will be gathered
894 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000895
Georg Brandl682d7e02010-10-06 10:26:05 +0000896 >>> parser = argparse.ArgumentParser()
897 >>> parser.add_argument('--foo', nargs=2)
898 >>> parser.add_argument('bar', nargs=1)
899 >>> parser.parse_args('c --foo a b'.split())
900 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000901
Georg Brandl682d7e02010-10-06 10:26:05 +0000902 Note that ``nargs=1`` produces a list of one item. This is different from
903 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000904
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200905.. index:: single: ? (question mark); in argparse module
906
Éric Araujofde92422011-08-19 01:30:26 +0200907* ``'?'``. One argument will be consumed from the command line if possible, and
908 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000909 default_ will be produced. Note that for optional arguments, there is an
910 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200911 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000912 examples to illustrate this::
913
914 >>> parser = argparse.ArgumentParser()
915 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
916 >>> parser.add_argument('bar', nargs='?', default='d')
Martin Panterf5e60482016-04-26 11:41:25 +0000917 >>> parser.parse_args(['XX', '--foo', 'YY'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000918 Namespace(bar='XX', foo='YY')
Martin Panterf5e60482016-04-26 11:41:25 +0000919 >>> parser.parse_args(['XX', '--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000920 Namespace(bar='XX', foo='c')
Martin Panterf5e60482016-04-26 11:41:25 +0000921 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000922 Namespace(bar='d', foo='d')
923
924 One of the more common uses of ``nargs='?'`` is to allow optional input and
925 output files::
926
927 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000928 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
929 ... default=sys.stdin)
930 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
931 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000932 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000933 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
934 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000935 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000936 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
937 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000938
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200939.. index:: single: * (asterisk); in argparse module
940
Éric Araujod9d7bca2011-08-10 04:19:03 +0200941* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000942 it generally doesn't make much sense to have more than one positional argument
943 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
944 possible. For example::
945
946 >>> parser = argparse.ArgumentParser()
947 >>> parser.add_argument('--foo', nargs='*')
948 >>> parser.add_argument('--bar', nargs='*')
949 >>> parser.add_argument('baz', nargs='*')
950 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
951 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
952
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200953.. index:: single: + (plus); in argparse module
954
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000955* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
956 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200957 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000958
959 >>> parser = argparse.ArgumentParser(prog='PROG')
960 >>> parser.add_argument('foo', nargs='+')
Martin Panterf5e60482016-04-26 11:41:25 +0000961 >>> parser.parse_args(['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000962 Namespace(foo=['a', 'b'])
Martin Panterf5e60482016-04-26 11:41:25 +0000963 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000964 usage: PROG [-h] foo [foo ...]
suic8604e82932018-04-11 20:45:04 +0200965 PROG: error: the following arguments are required: foo
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000966
Éric Araujod9d7bca2011-08-10 04:19:03 +0200967If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200968is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000969will be consumed and a single item (not a list) will be produced.
970
971
972const
973^^^^^
974
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300975The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
976constant values that are not read from the command line but are required for
977the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000978
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300979* When :meth:`~ArgumentParser.add_argument` is called with
980 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100981 ``const`` value to one of the attributes of the object returned by
982 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000983
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300984* When :meth:`~ArgumentParser.add_argument` is called with option strings
985 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200986 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300987 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200988 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300989 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000990
Martin Panterb4912b82016-04-09 03:49:48 +0000991With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panter119e5022016-04-16 09:28:57 +0000992keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000993
994
995default
996^^^^^^^
997
998All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300999command line. The ``default`` keyword argument of
1000:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +02001001specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001002For optional arguments, the ``default`` value is used when the option string
1003was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001004
1005 >>> parser = argparse.ArgumentParser()
1006 >>> parser.add_argument('--foo', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +00001007 >>> parser.parse_args(['--foo', '2'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001008 Namespace(foo='2')
Martin Panterf5e60482016-04-26 11:41:25 +00001009 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001010 Namespace(foo=42)
1011
Raymond Hettinger752cdf22020-12-06 18:29:08 -08001012If the target namespace already has an attribute set, the action *default*
1013will not over write it::
1014
1015 >>> parser = argparse.ArgumentParser()
1016 >>> parser.add_argument('--foo', default=42)
1017 >>> parser.parse_args([], namespace=argparse.Namespace(foo=101))
1018 Namespace(foo=101)
1019
Barry Warsaw1dedd0a2012-09-25 10:37:58 -04001020If the ``default`` value is a string, the parser parses the value as if it
1021were a command-line argument. In particular, the parser applies any type_
1022conversion argument, if provided, before setting the attribute on the
1023:class:`Namespace` return value. Otherwise, the parser uses the value as is::
1024
1025 >>> parser = argparse.ArgumentParser()
1026 >>> parser.add_argument('--length', default='10', type=int)
1027 >>> parser.add_argument('--width', default=10.5, type=int)
1028 >>> parser.parse_args()
1029 Namespace(length=10, width=10.5)
1030
Éric Araujo543edbd2011-08-19 01:45:12 +02001031For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +02001032is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001033
1034 >>> parser = argparse.ArgumentParser()
1035 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +00001036 >>> parser.parse_args(['a'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001037 Namespace(foo='a')
Martin Panterf5e60482016-04-26 11:41:25 +00001038 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001039 Namespace(foo=42)
1040
1041
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001042Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
Julien Palard78553132018-03-28 23:14:15 +02001043command-line argument was not present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001044
1045 >>> parser = argparse.ArgumentParser()
1046 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
1047 >>> parser.parse_args([])
1048 Namespace()
1049 >>> parser.parse_args(['--foo', '1'])
1050 Namespace(foo='1')
1051
1052
1053type
1054^^^^
1055
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001056By default, the parser reads command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001057strings. However, quite often the command-line string should instead be
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001058interpreted as another type, such as a :class:`float` or :class:`int`. The
1059``type`` keyword for :meth:`~ArgumentParser.add_argument` allows any
1060necessary type-checking and type conversions to be performed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001061
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001062If the type_ keyword is used with the default_ keyword, the type converter
1063is only applied if the default is a string.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001064
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001065The argument to ``type`` can be any callable that accepts a single string.
1066If the function raises :exc:`ArgumentTypeError`, :exc:`TypeError`, or
1067:exc:`ValueError`, the exception is caught and a nicely formatted error
1068message is displayed. No other exception types are handled.
Barry Warsaw1dedd0a2012-09-25 10:37:58 -04001069
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001070Common built-in types and functions can be used as type converters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001071
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001072.. testcode::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001073
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001074 import argparse
1075 import pathlib
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001076
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001077 parser = argparse.ArgumentParser()
1078 parser.add_argument('count', type=int)
1079 parser.add_argument('distance', type=float)
1080 parser.add_argument('street', type=ascii)
1081 parser.add_argument('code_point', type=ord)
1082 parser.add_argument('source_file', type=open)
1083 parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-1'))
1084 parser.add_argument('datapath', type=pathlib.Path)
1085
1086User defined functions can be used as well:
1087
1088.. doctest::
1089
1090 >>> def hyphenated(string):
1091 ... return '-'.join([word[:4] for word in string.casefold().split()])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001092 ...
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001093 >>> parser = argparse.ArgumentParser()
1094 >>> _ = parser.add_argument('short_title', type=hyphenated)
1095 >>> parser.parse_args(['"The Tale of Two Cities"'])
1096 Namespace(short_title='"the-tale-of-two-citi')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001097
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001098The :func:`bool` function is not recommended as a type converter. All it does
1099is convert empty strings to ``False`` and non-empty strings to ``True``.
1100This is usually not what is desired.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001101
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001102In general, the ``type`` keyword is a convenience that should only be used for
1103simple conversions that can only raise one of the three supported exceptions.
1104Anything with more interesting error-handling or resource management should be
1105done downstream after the arguments are parsed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001106
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001107For example, JSON or YAML conversions have complex error cases that require
Miss Islington (bot)6d604492021-09-28 07:07:13 -07001108better reporting than can be given by the ``type`` keyword. A
Raymond Hettingerb0398a42020-12-20 10:14:54 -08001109:exc:`~json.JSONDecodeError` would not be well formatted and a
1110:exc:`FileNotFound` exception would not be handled at all.
1111
1112Even :class:`~argparse.FileType` has its limitations for use with the ``type``
1113keyword. If one argument uses *FileType* and then a subsequent argument fails,
1114an error is reported but the file is not automatically closed. In this case, it
1115would be better to wait until after the parser has run and then use the
1116:keyword:`with`-statement to manage the files.
1117
1118For type checkers that simply check against a fixed set of values, consider
1119using the choices_ keyword instead.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001120
1121
1122choices
1123^^^^^^^
1124
Éric Araujod9d7bca2011-08-10 04:19:03 +02001125Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001126These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001127argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001128parsed, argument values will be checked, and an error message will be displayed
1129if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001130
Chris Jerdonek174ef672013-01-11 19:26:44 -08001131 >>> parser = argparse.ArgumentParser(prog='game.py')
1132 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1133 >>> parser.parse_args(['rock'])
1134 Namespace(move='rock')
1135 >>> parser.parse_args(['fire'])
1136 usage: game.py [-h] {rock,paper,scissors}
1137 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1138 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001139
Chris Jerdonek174ef672013-01-11 19:26:44 -08001140Note that inclusion in the *choices* container is checked after any type_
1141conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001142container should match the type_ specified::
1143
Chris Jerdonek174ef672013-01-11 19:26:44 -08001144 >>> parser = argparse.ArgumentParser(prog='doors.py')
1145 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1146 >>> print(parser.parse_args(['3']))
1147 Namespace(door=3)
1148 >>> parser.parse_args(['4'])
1149 usage: doors.py [-h] {1,2,3}
1150 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001151
Raymond Hettinger84125fe2019-08-29 00:58:08 -07001152Any container can be passed as the *choices* value, so :class:`list` objects,
1153:class:`set` objects, and custom containers are all supported.
Vincent Férotin344c2a72020-06-20 14:55:05 +02001154
Raymond Hettinger7f82f222020-11-30 09:55:13 -08001155Use of :class:`enum.Enum` is not recommended because it is difficult to
1156control its appearance in usage, help, and error messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001157
Raymond Hettinger6afb7302020-12-22 09:24:26 -08001158Formatted choices overrides the default *metavar* which is normally derived
1159from *dest*. This is usually what you want because the user never sees the
1160*dest* parameter. If this display isn't desirable (perhaps because there are
1161many choices), just specify an explicit metavar_.
1162
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001163
1164required
1165^^^^^^^^
1166
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001167In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001168indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001169To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001170keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001171
1172 >>> parser = argparse.ArgumentParser()
1173 >>> parser.add_argument('--foo', required=True)
1174 >>> parser.parse_args(['--foo', 'BAR'])
1175 Namespace(foo='BAR')
1176 >>> parser.parse_args([])
SarahPythonista8784d332020-08-28 11:47:58 -07001177 usage: [-h] --foo FOO
1178 : error: the following arguments are required: --foo
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001179
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001180As the example shows, if an option is marked as ``required``,
1181:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1182present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001183
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001184.. note::
1185
1186 Required options are generally considered bad form because users expect
1187 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001188
1189
1190help
1191^^^^
1192
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001193The ``help`` value is a string containing a brief description of the argument.
1194When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001195command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001196argument::
1197
1198 >>> parser = argparse.ArgumentParser(prog='frobble')
1199 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001200 ... help='foo the bars before frobbling')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001201 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001202 ... help='one of the bars to be frobbled')
Martin Panterf5e60482016-04-26 11:41:25 +00001203 >>> parser.parse_args(['-h'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001204 usage: frobble [-h] [--foo] bar [bar ...]
1205
1206 positional arguments:
1207 bar one of the bars to be frobbled
1208
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001209 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001210 -h, --help show this help message and exit
1211 --foo foo the bars before frobbling
1212
1213The ``help`` strings can include various format specifiers to avoid repetition
1214of things like the program name or the argument default_. The available
1215specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001216:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001217
1218 >>> parser = argparse.ArgumentParser(prog='frobble')
1219 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001220 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001221 >>> parser.print_help()
1222 usage: frobble [-h] [bar]
1223
1224 positional arguments:
1225 bar the bar to frobble (default: 42)
1226
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001227 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001228 -h, --help show this help message and exit
1229
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001230As the help string supports %-formatting, if you want a literal ``%`` to appear
1231in the help string, you must escape it as ``%%``.
1232
Sandro Tosiea320ab2012-01-03 18:37:03 +01001233:mod:`argparse` supports silencing the help entry for certain options, by
1234setting the ``help`` value to ``argparse.SUPPRESS``::
1235
1236 >>> parser = argparse.ArgumentParser(prog='frobble')
1237 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1238 >>> parser.print_help()
1239 usage: frobble [-h]
1240
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001241 options:
Sandro Tosiea320ab2012-01-03 18:37:03 +01001242 -h, --help show this help message and exit
1243
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001244
1245metavar
1246^^^^^^^
1247
Sandro Tosi32587fb2013-01-11 10:49:00 +01001248When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001249to each expected argument. By default, ArgumentParser objects use the dest_
1250value as the "name" of each object. By default, for positional argument
1251actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001252the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001253``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001254optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001255will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001256
1257 >>> parser = argparse.ArgumentParser()
1258 >>> parser.add_argument('--foo')
1259 >>> parser.add_argument('bar')
1260 >>> parser.parse_args('X --foo Y'.split())
1261 Namespace(bar='X', foo='Y')
1262 >>> parser.print_help()
1263 usage: [-h] [--foo FOO] bar
1264
1265 positional arguments:
1266 bar
1267
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001268 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001269 -h, --help show this help message and exit
1270 --foo FOO
1271
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001272An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001273
1274 >>> parser = argparse.ArgumentParser()
1275 >>> parser.add_argument('--foo', metavar='YYY')
1276 >>> parser.add_argument('bar', metavar='XXX')
1277 >>> parser.parse_args('X --foo Y'.split())
1278 Namespace(bar='X', foo='Y')
1279 >>> parser.print_help()
1280 usage: [-h] [--foo YYY] XXX
1281
1282 positional arguments:
1283 XXX
1284
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001285 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001286 -h, --help show this help message and exit
1287 --foo YYY
1288
1289Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001290attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1291by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001292
1293Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001294Providing a tuple to ``metavar`` specifies a different display for each of the
1295arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001296
1297 >>> parser = argparse.ArgumentParser(prog='PROG')
1298 >>> parser.add_argument('-x', nargs=2)
1299 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1300 >>> parser.print_help()
1301 usage: PROG [-h] [-x X X] [--foo bar baz]
1302
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001303 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001304 -h, --help show this help message and exit
1305 -x X X
1306 --foo bar baz
1307
1308
1309dest
1310^^^^
1311
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001312Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001313object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1314attribute is determined by the ``dest`` keyword argument of
1315:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1316``dest`` is normally supplied as the first argument to
1317:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001318
1319 >>> parser = argparse.ArgumentParser()
1320 >>> parser.add_argument('bar')
Martin Panterf5e60482016-04-26 11:41:25 +00001321 >>> parser.parse_args(['XXX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001322 Namespace(bar='XXX')
1323
1324For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001325the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001326taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001327string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001328the first short option string by stripping the initial ``-`` character. Any
1329internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001330the string is a valid attribute name. The examples below illustrate this
1331behavior::
1332
1333 >>> parser = argparse.ArgumentParser()
1334 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1335 >>> parser.add_argument('-x', '-y')
1336 >>> parser.parse_args('-f 1 -x 2'.split())
1337 Namespace(foo_bar='1', x='2')
1338 >>> parser.parse_args('--foo 1 -y 2'.split())
1339 Namespace(foo_bar='1', x='2')
1340
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001341``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001342
1343 >>> parser = argparse.ArgumentParser()
1344 >>> parser.add_argument('--foo', dest='bar')
1345 >>> parser.parse_args('--foo XXX'.split())
1346 Namespace(bar='XXX')
1347
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001348Action classes
1349^^^^^^^^^^^^^^
1350
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001351Action classes implement the Action API, a callable which returns a callable
1352which processes arguments from the command-line. Any object which follows
1353this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001354:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001355
Terry Jan Reedyee558262014-08-23 22:21:47 -04001356.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1357 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001358 metavar=None)
1359
1360Action objects are used by an ArgumentParser to represent the information
1361needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001362command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001363plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001364except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001365
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001366Instances of Action (or return value of any callable to the ``action``
1367parameter) should have attributes "dest", "option_strings", "default", "type",
1368"required", "help", etc. defined. The easiest way to ensure these attributes
1369are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001370
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001371Action instances should be callable, so subclasses must override the
1372``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001373
1374* ``parser`` - The ArgumentParser object which contains this action.
1375
1376* ``namespace`` - The :class:`Namespace` object that will be returned by
1377 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1378 object using :func:`setattr`.
1379
1380* ``values`` - The associated command-line arguments, with any type conversions
1381 applied. Type conversions are specified with the type_ keyword argument to
1382 :meth:`~ArgumentParser.add_argument`.
1383
1384* ``option_string`` - The option string that was used to invoke this action.
1385 The ``option_string`` argument is optional, and will be absent if the action
1386 is associated with a positional argument.
1387
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001388The ``__call__`` method may perform arbitrary actions, but will typically set
1389attributes on the ``namespace`` based on ``dest`` and ``values``.
1390
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02001391Action subclasses can define a ``format_usage`` method that takes no argument
1392and return a string which will be used when printing the usage of the program.
1393If such method is not provided, a sensible default will be used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001394
1395The parse_args() method
1396-----------------------
1397
Georg Brandle0bf91d2010-10-17 10:34:28 +00001398.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001399
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001400 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001401 namespace. Return the populated namespace.
1402
1403 Previous calls to :meth:`add_argument` determine exactly what objects are
1404 created and how they are assigned. See the documentation for
1405 :meth:`add_argument` for details.
1406
R. David Murray0c7983e2017-09-04 16:17:26 -04001407 * args_ - List of strings to parse. The default is taken from
1408 :data:`sys.argv`.
1409
1410 * namespace_ - An object to take the attributes. The default is a new empty
1411 :class:`Namespace` object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001412
Georg Brandle0bf91d2010-10-17 10:34:28 +00001413
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001414Option value syntax
1415^^^^^^^^^^^^^^^^^^^
1416
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001417The :meth:`~ArgumentParser.parse_args` method supports several ways of
1418specifying the value of an option (if it takes one). In the simplest case, the
1419option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001420
1421 >>> parser = argparse.ArgumentParser(prog='PROG')
1422 >>> parser.add_argument('-x')
1423 >>> parser.add_argument('--foo')
Martin Panterf5e60482016-04-26 11:41:25 +00001424 >>> parser.parse_args(['-x', 'X'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001425 Namespace(foo=None, x='X')
Martin Panterf5e60482016-04-26 11:41:25 +00001426 >>> parser.parse_args(['--foo', 'FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001427 Namespace(foo='FOO', x=None)
1428
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001429For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001430and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001431separate them::
1432
Martin Panterf5e60482016-04-26 11:41:25 +00001433 >>> parser.parse_args(['--foo=FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001434 Namespace(foo='FOO', x=None)
1435
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001436For short options (options only one character long), the option and its value
1437can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001438
Martin Panterf5e60482016-04-26 11:41:25 +00001439 >>> parser.parse_args(['-xX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001440 Namespace(foo=None, x='X')
1441
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001442Several short options can be joined together, using only a single ``-`` prefix,
1443as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001444
1445 >>> parser = argparse.ArgumentParser(prog='PROG')
1446 >>> parser.add_argument('-x', action='store_true')
1447 >>> parser.add_argument('-y', action='store_true')
1448 >>> parser.add_argument('-z')
Martin Panterf5e60482016-04-26 11:41:25 +00001449 >>> parser.parse_args(['-xyzZ'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001450 Namespace(x=True, y=True, z='Z')
1451
1452
1453Invalid arguments
1454^^^^^^^^^^^^^^^^^
1455
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001456While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1457variety of errors, including ambiguous options, invalid types, invalid options,
1458wrong number of positional arguments, etc. When it encounters such an error,
1459it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001460
1461 >>> parser = argparse.ArgumentParser(prog='PROG')
1462 >>> parser.add_argument('--foo', type=int)
1463 >>> parser.add_argument('bar', nargs='?')
1464
1465 >>> # invalid type
1466 >>> parser.parse_args(['--foo', 'spam'])
1467 usage: PROG [-h] [--foo FOO] [bar]
1468 PROG: error: argument --foo: invalid int value: 'spam'
1469
1470 >>> # invalid option
1471 >>> parser.parse_args(['--bar'])
1472 usage: PROG [-h] [--foo FOO] [bar]
1473 PROG: error: no such option: --bar
1474
1475 >>> # wrong number of arguments
1476 >>> parser.parse_args(['spam', 'badger'])
1477 usage: PROG [-h] [--foo FOO] [bar]
1478 PROG: error: extra arguments found: badger
1479
1480
Éric Araujo543edbd2011-08-19 01:45:12 +02001481Arguments containing ``-``
1482^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001483
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001484The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1485the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001486ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001487attempt to specify an option or an attempt to provide a positional argument.
1488The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001489arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001490there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001491
1492 >>> parser = argparse.ArgumentParser(prog='PROG')
1493 >>> parser.add_argument('-x')
1494 >>> parser.add_argument('foo', nargs='?')
1495
1496 >>> # no negative number options, so -1 is a positional argument
1497 >>> parser.parse_args(['-x', '-1'])
1498 Namespace(foo=None, x='-1')
1499
1500 >>> # no negative number options, so -1 and -5 are positional arguments
1501 >>> parser.parse_args(['-x', '-1', '-5'])
1502 Namespace(foo='-5', x='-1')
1503
1504 >>> parser = argparse.ArgumentParser(prog='PROG')
1505 >>> parser.add_argument('-1', dest='one')
1506 >>> parser.add_argument('foo', nargs='?')
1507
1508 >>> # negative number options present, so -1 is an option
1509 >>> parser.parse_args(['-1', 'X'])
1510 Namespace(foo=None, one='X')
1511
1512 >>> # negative number options present, so -2 is an option
1513 >>> parser.parse_args(['-2'])
1514 usage: PROG [-h] [-1 ONE] [foo]
1515 PROG: error: no such option: -2
1516
1517 >>> # negative number options present, so both -1s are options
1518 >>> parser.parse_args(['-1', '-1'])
1519 usage: PROG [-h] [-1 ONE] [foo]
1520 PROG: error: argument -1: expected one argument
1521
Éric Araujo543edbd2011-08-19 01:45:12 +02001522If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001523like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001524:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1525argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001526
1527 >>> parser.parse_args(['--', '-f'])
1528 Namespace(foo='-f', one=None)
1529
Eli Benderskyf3114532013-12-02 05:49:54 -08001530.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001531
Eli Benderskyf3114532013-12-02 05:49:54 -08001532Argument abbreviations (prefix matching)
1533^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001534
Berker Peksag8089cd62015-02-14 01:39:17 +02001535The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>`
1536allows long options to be abbreviated to a prefix, if the abbreviation is
1537unambiguous (the prefix matches a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001538
1539 >>> parser = argparse.ArgumentParser(prog='PROG')
1540 >>> parser.add_argument('-bacon')
1541 >>> parser.add_argument('-badger')
1542 >>> parser.parse_args('-bac MMM'.split())
1543 Namespace(bacon='MMM', badger=None)
1544 >>> parser.parse_args('-bad WOOD'.split())
1545 Namespace(bacon=None, badger='WOOD')
1546 >>> parser.parse_args('-ba BA'.split())
1547 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1548 PROG: error: ambiguous option: -ba could match -badger, -bacon
1549
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001550An error is produced for arguments that could produce more than one options.
Berker Peksag8089cd62015-02-14 01:39:17 +02001551This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001552
R. David Murray0c7983e2017-09-04 16:17:26 -04001553.. _args:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001554
1555Beyond ``sys.argv``
1556^^^^^^^^^^^^^^^^^^^
1557
Éric Araujod9d7bca2011-08-10 04:19:03 +02001558Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001559of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001560:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1561interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001562
1563 >>> parser = argparse.ArgumentParser()
1564 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001565 ... 'integers', metavar='int', type=int, choices=range(10),
Serhiy Storchakadba90392016-05-10 12:01:23 +03001566 ... nargs='+', help='an integer in the range 0..9')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001567 >>> parser.add_argument(
1568 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001569 ... default=max, help='sum the integers (default: find the max)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001570 >>> parser.parse_args(['1', '2', '3', '4'])
1571 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panterf5e60482016-04-26 11:41:25 +00001572 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001573 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1574
R. David Murray0c7983e2017-09-04 16:17:26 -04001575.. _namespace:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001576
Steven Bethardd8f2d502011-03-26 19:50:06 +01001577The Namespace object
1578^^^^^^^^^^^^^^^^^^^^
1579
Éric Araujo63b18a42011-07-29 17:59:17 +02001580.. class:: Namespace
1581
1582 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1583 an object holding attributes and return it.
1584
1585This class is deliberately simple, just an :class:`object` subclass with a
1586readable string representation. If you prefer to have dict-like view of the
1587attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001588
1589 >>> parser = argparse.ArgumentParser()
1590 >>> parser.add_argument('--foo')
1591 >>> args = parser.parse_args(['--foo', 'BAR'])
1592 >>> vars(args)
1593 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001594
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001595It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001596already existing object, rather than a new :class:`Namespace` object. This can
1597be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001598
Éric Araujo28053fb2010-11-22 03:09:19 +00001599 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001600 ... pass
1601 ...
1602 >>> c = C()
1603 >>> parser = argparse.ArgumentParser()
1604 >>> parser.add_argument('--foo')
1605 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1606 >>> c.foo
1607 'BAR'
1608
1609
1610Other utilities
1611---------------
1612
1613Sub-commands
1614^^^^^^^^^^^^
1615
Georg Brandlfc9a1132013-10-06 18:51:39 +02001616.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1617 [parser_class], [action], \
Anthony Sottilecc182582018-08-23 20:08:54 -07001618 [option_string], [dest], [required], \
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001619 [help], [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001620
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001621 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001622 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001623 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001624 this way can be a particularly good idea when a program performs several
1625 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001626 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001627 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001628 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001629 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1630 command name and any :class:`ArgumentParser` constructor arguments, and
1631 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001632
Georg Brandlfc9a1132013-10-06 18:51:39 +02001633 Description of parameters:
1634
1635 * title - title for the sub-parser group in help output; by default
1636 "subcommands" if description is provided, otherwise uses title for
1637 positional arguments
1638
1639 * description - description for the sub-parser group in help output, by
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001640 default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001641
1642 * prog - usage information that will be displayed with sub-command help,
1643 by default the name of the program and any positional arguments before the
1644 subparser argument
1645
1646 * parser_class - class which will be used to create sub-parser instances, by
1647 default the class of the current parser (e.g. ArgumentParser)
1648
Berker Peksag5a494f62015-01-20 06:45:53 +02001649 * action_ - the basic type of action to be taken when this argument is
1650 encountered at the command line
1651
1652 * dest_ - name of the attribute under which sub-command name will be
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001653 stored; by default ``None`` and no value is stored
Georg Brandlfc9a1132013-10-06 18:51:39 +02001654
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001655 * required_ - Whether or not a subcommand must be provided, by default
Adam J. Stewart9e719172019-10-06 21:08:48 -05001656 ``False`` (added in 3.7)
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001657
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001658 * help_ - help for sub-parser group in help output, by default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001659
Berker Peksag5a494f62015-01-20 06:45:53 +02001660 * metavar_ - string presenting available sub-commands in help; by default it
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001661 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
Georg Brandlfc9a1132013-10-06 18:51:39 +02001662
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001663 Some example usage::
1664
1665 >>> # create the top-level parser
1666 >>> parser = argparse.ArgumentParser(prog='PROG')
1667 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1668 >>> subparsers = parser.add_subparsers(help='sub-command help')
1669 >>>
1670 >>> # create the parser for the "a" command
1671 >>> parser_a = subparsers.add_parser('a', help='a help')
1672 >>> parser_a.add_argument('bar', type=int, help='bar help')
1673 >>>
1674 >>> # create the parser for the "b" command
1675 >>> parser_b = subparsers.add_parser('b', help='b help')
1676 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1677 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001678 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001679 >>> parser.parse_args(['a', '12'])
1680 Namespace(bar=12, foo=False)
1681 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1682 Namespace(baz='Z', foo=True)
1683
1684 Note that the object returned by :meth:`parse_args` will only contain
1685 attributes for the main parser and the subparser that was selected by the
1686 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001687 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1688 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001689 ``baz`` attributes are present.
1690
1691 Similarly, when a help message is requested from a subparser, only the help
1692 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001693 include parent parser or sibling parser messages. (A help message for each
1694 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001695 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001696
1697 ::
1698
1699 >>> parser.parse_args(['--help'])
1700 usage: PROG [-h] [--foo] {a,b} ...
1701
1702 positional arguments:
1703 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001704 a a help
1705 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001706
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001707 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001708 -h, --help show this help message and exit
1709 --foo foo help
1710
1711 >>> parser.parse_args(['a', '--help'])
1712 usage: PROG a [-h] bar
1713
1714 positional arguments:
1715 bar bar help
1716
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001717 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001718 -h, --help show this help message and exit
1719
1720 >>> parser.parse_args(['b', '--help'])
1721 usage: PROG b [-h] [--baz {X,Y,Z}]
1722
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001723 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001724 -h, --help show this help message and exit
1725 --baz {X,Y,Z} baz help
1726
1727 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1728 keyword arguments. When either is present, the subparser's commands will
1729 appear in their own group in the help output. For example::
1730
1731 >>> parser = argparse.ArgumentParser()
1732 >>> subparsers = parser.add_subparsers(title='subcommands',
1733 ... description='valid subcommands',
1734 ... help='additional help')
1735 >>> subparsers.add_parser('foo')
1736 >>> subparsers.add_parser('bar')
1737 >>> parser.parse_args(['-h'])
1738 usage: [-h] {foo,bar} ...
1739
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001740 options:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001741 -h, --help show this help message and exit
1742
1743 subcommands:
1744 valid subcommands
1745
1746 {foo,bar} additional help
1747
Steven Bethardfd311a72010-12-18 11:19:23 +00001748 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1749 which allows multiple strings to refer to the same subparser. This example,
1750 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1751
1752 >>> parser = argparse.ArgumentParser()
1753 >>> subparsers = parser.add_subparsers()
1754 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1755 >>> checkout.add_argument('foo')
1756 >>> parser.parse_args(['co', 'bar'])
1757 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001758
1759 One particularly effective way of handling sub-commands 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 >>> # sub-command functions
1765 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001766 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001767 ...
1768 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001769 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001770 ...
1771 >>> # create the top-level parser
1772 >>> parser = argparse.ArgumentParser()
1773 >>> subparsers = parser.add_subparsers()
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
Steven Bethardfd311a72010-12-18 11:19:23 +00001796 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001797 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::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001802
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
Adam J. Stewart9e719172019-10-06 21:08:48 -05001812 .. versionchanged:: 3.7
1813 New *required* keyword argument.
1814
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001815
1816FileType objects
1817^^^^^^^^^^^^^^^^
1818
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001819.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001820
1821 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001822 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001823 :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)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001826
Éric Araujoc3ef0372012-02-20 01:44:55 +01001827 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001828 >>> 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'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001832
1833 FileType objects understand the pseudo-argument ``'-'`` and automatically
1834 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001835 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001836
Éric Araujoc3ef0372012-02-20 01:44:55 +01001837 >>> 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'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001841
R David Murrayfced3ec2013-12-31 11:18:01 -05001842 .. versionadded:: 3.4
1843 The *encodings* and *errors* keyword arguments.
1844
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001845
1846Argument groups
1847^^^^^^^^^^^^^^^
1848
Georg Brandle0bf91d2010-10-17 10:34:28 +00001849.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001850
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001851 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001852 "positional arguments" and "optional arguments" when displaying help
1853 messages. When there is a better conceptual grouping of arguments than this
1854 default one, appropriate groups can be created using the
1855 :meth:`add_argument_group` method::
1856
1857 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1858 >>> group = parser.add_argument_group('group')
1859 >>> group.add_argument('--foo', help='foo help')
1860 >>> group.add_argument('bar', help='bar help')
1861 >>> parser.print_help()
1862 usage: PROG [--foo FOO] bar
1863
1864 group:
1865 bar bar help
1866 --foo FOO foo help
1867
1868 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001869 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1870 :class:`ArgumentParser`. When an argument is added to the group, the parser
1871 treats it just like a normal argument, but displays the argument in a
1872 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001873 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001874 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001875
1876 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1877 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1878 >>> group1.add_argument('foo', help='foo help')
1879 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1880 >>> group2.add_argument('--bar', help='bar help')
1881 >>> parser.print_help()
1882 usage: PROG [--bar BAR] foo
1883
1884 group1:
1885 group1 description
1886
1887 foo foo help
1888
1889 group2:
1890 group2 description
1891
1892 --bar BAR bar help
1893
Sandro Tosi99e7d072012-03-26 19:36:23 +02001894 Note that any arguments not in your user-defined groups will end up back
1895 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001896
1897
1898Mutual exclusion
1899^^^^^^^^^^^^^^^^
1900
Georg Brandled86ff82013-10-06 13:09:59 +02001901.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001902
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001903 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1904 one of the arguments in the mutually exclusive group was present on the
1905 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001906
1907 >>> parser = argparse.ArgumentParser(prog='PROG')
1908 >>> group = parser.add_mutually_exclusive_group()
1909 >>> group.add_argument('--foo', action='store_true')
1910 >>> group.add_argument('--bar', action='store_false')
1911 >>> parser.parse_args(['--foo'])
1912 Namespace(bar=True, foo=True)
1913 >>> parser.parse_args(['--bar'])
1914 Namespace(bar=False, foo=False)
1915 >>> parser.parse_args(['--foo', '--bar'])
1916 usage: PROG [-h] [--foo | --bar]
1917 PROG: error: argument --bar: not allowed with argument --foo
1918
Georg Brandle0bf91d2010-10-17 10:34:28 +00001919 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001920 argument, to indicate that at least one of the mutually exclusive arguments
1921 is required::
1922
1923 >>> parser = argparse.ArgumentParser(prog='PROG')
1924 >>> group = parser.add_mutually_exclusive_group(required=True)
1925 >>> group.add_argument('--foo', action='store_true')
1926 >>> group.add_argument('--bar', action='store_false')
1927 >>> parser.parse_args([])
1928 usage: PROG [-h] (--foo | --bar)
1929 PROG: error: one of the arguments --foo --bar is required
1930
1931 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001932 *title* and *description* arguments of
1933 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001934
1935
1936Parser defaults
1937^^^^^^^^^^^^^^^
1938
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001939.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001940
1941 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001942 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001943 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001944 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001945 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001946
1947 >>> parser = argparse.ArgumentParser()
1948 >>> parser.add_argument('foo', type=int)
1949 >>> parser.set_defaults(bar=42, baz='badger')
1950 >>> parser.parse_args(['736'])
1951 Namespace(bar=42, baz='badger', foo=736)
1952
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001953 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001954
1955 >>> parser = argparse.ArgumentParser()
1956 >>> parser.add_argument('--foo', default='bar')
1957 >>> parser.set_defaults(foo='spam')
1958 >>> parser.parse_args([])
1959 Namespace(foo='spam')
1960
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001961 Parser-level defaults can be particularly useful when working with multiple
1962 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1963 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001964
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001965.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001966
1967 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001968 :meth:`~ArgumentParser.add_argument` or by
1969 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001970
1971 >>> parser = argparse.ArgumentParser()
1972 >>> parser.add_argument('--foo', default='badger')
1973 >>> parser.get_default('foo')
1974 'badger'
1975
1976
1977Printing help
1978^^^^^^^^^^^^^
1979
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001980In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1981care of formatting and printing any usage or error messages. However, several
1982formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001983
Georg Brandle0bf91d2010-10-17 10:34:28 +00001984.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001985
1986 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001987 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001988 assumed.
1989
Georg Brandle0bf91d2010-10-17 10:34:28 +00001990.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001991
1992 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001993 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001994 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001995
1996There are also variants of these methods that simply return a string instead of
1997printing it:
1998
Georg Brandle0bf91d2010-10-17 10:34:28 +00001999.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002000
2001 Return a string containing a brief description of how the
2002 :class:`ArgumentParser` should be invoked on the command line.
2003
Georg Brandle0bf91d2010-10-17 10:34:28 +00002004.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002005
2006 Return a string containing a help message, including the program usage and
2007 information about the arguments registered with the :class:`ArgumentParser`.
2008
2009
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002010Partial parsing
2011^^^^^^^^^^^^^^^
2012
Georg Brandle0bf91d2010-10-17 10:34:28 +00002013.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002014
Georg Brandl69518bc2011-04-16 16:44:54 +02002015Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002016the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002017:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002018:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
2019extra arguments are present. Instead, it returns a two item tuple containing
2020the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002021
2022::
2023
2024 >>> parser = argparse.ArgumentParser()
2025 >>> parser.add_argument('--foo', action='store_true')
2026 >>> parser.add_argument('bar')
2027 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
2028 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
2029
Eli Benderskyf3114532013-12-02 05:49:54 -08002030.. warning::
2031 :ref:`Prefix matching <prefix-matching>` rules apply to
2032 :meth:`parse_known_args`. The parser may consume an option even if it's just
2033 a prefix of one of its known options, instead of leaving it in the remaining
2034 arguments list.
2035
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002036
2037Customizing file parsing
2038^^^^^^^^^^^^^^^^^^^^^^^^
2039
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002040.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002041
Georg Brandle0bf91d2010-10-17 10:34:28 +00002042 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002043 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft8b852f12014-05-20 12:58:38 -04002044 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002045 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002046
Georg Brandle0bf91d2010-10-17 10:34:28 +00002047 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002048 the argument file. It returns a list of arguments parsed from this string.
2049 The method is called once per line read from the argument file, in order.
2050
2051 A useful override of this method is one that treats each space-separated word
Berker Peksag5493e472016-10-17 06:14:17 +03002052 as an argument. The following example demonstrates how to do this::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002053
Berker Peksag5493e472016-10-17 06:14:17 +03002054 class MyArgumentParser(argparse.ArgumentParser):
2055 def convert_arg_line_to_args(self, arg_line):
2056 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002057
2058
Georg Brandl93754922010-10-17 10:28:04 +00002059Exiting methods
2060^^^^^^^^^^^^^^^
2061
2062.. method:: ArgumentParser.exit(status=0, message=None)
2063
2064 This method terminates the program, exiting with the specified *status*
Hai Shib1a2abd2019-09-12 10:34:24 -05002065 and, if given, it prints a *message* before that. The user can override
2066 this method to handle these steps differently::
2067
2068 class ErrorCatchingArgumentParser(argparse.ArgumentParser):
2069 def exit(self, status=0, message=None):
2070 if status:
2071 raise Exception(f'Exiting because of an error: {message}')
2072 exit(status)
Georg Brandl93754922010-10-17 10:28:04 +00002073
2074.. method:: ArgumentParser.error(message)
2075
2076 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08002077 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00002078
R. David Murray0f6b9d22017-09-06 20:25:40 -04002079
2080Intermixed parsing
2081^^^^^^^^^^^^^^^^^^
2082
2083.. method:: ArgumentParser.parse_intermixed_args(args=None, namespace=None)
2084.. method:: ArgumentParser.parse_known_intermixed_args(args=None, namespace=None)
2085
2086A number of Unix commands allow the user to intermix optional arguments with
2087positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args`
2088and :meth:`~ArgumentParser.parse_known_intermixed_args` methods
2089support this parsing style.
2090
2091These parsers do not support all the argparse features, and will raise
2092exceptions if unsupported features are used. In particular, subparsers,
2093``argparse.REMAINDER``, and mutually exclusive groups that include both
2094optionals and positionals are not supported.
2095
2096The following example shows the difference between
2097:meth:`~ArgumentParser.parse_known_args` and
2098:meth:`~ArgumentParser.parse_intermixed_args`: the former returns ``['2',
2099'3']`` as unparsed arguments, while the latter collects all the positionals
2100into ``rest``. ::
2101
2102 >>> parser = argparse.ArgumentParser()
2103 >>> parser.add_argument('--foo')
2104 >>> parser.add_argument('cmd')
2105 >>> parser.add_argument('rest', nargs='*', type=int)
2106 >>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
2107 (Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
2108 >>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
2109 Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])
2110
2111:meth:`~ArgumentParser.parse_known_intermixed_args` returns a two item tuple
2112containing the populated namespace and the list of remaining argument strings.
2113:meth:`~ArgumentParser.parse_intermixed_args` raises an error if there are any
2114remaining unparsed argument strings.
2115
2116.. versionadded:: 3.7
2117
Raymond Hettinger677e10a2010-12-07 06:45:30 +00002118.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00002119
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002120Upgrading optparse code
2121-----------------------
2122
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002123Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002124with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
2125transparently, particularly with the changes required to support the new
2126``nargs=`` specifiers and better usage messages. When most everything in
2127:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
2128longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002129
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03002130The :mod:`argparse` module improves on the standard library :mod:`optparse`
2131module in a number of ways including:
2132
2133* Handling positional arguments.
2134* Supporting sub-commands.
2135* Allowing alternative option prefixes like ``+`` and ``/``.
2136* Handling zero-or-more and one-or-more style arguments.
2137* Producing more informative usage messages.
2138* Providing a much simpler interface for custom ``type`` and ``action``.
2139
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002140A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002141
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002142* Replace all :meth:`optparse.OptionParser.add_option` calls with
2143 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002144
R David Murray5e0c5712012-03-30 18:07:42 -04002145* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00002146 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04002147 calls for the positional arguments. Keep in mind that what was previously
R. David Murray0c7983e2017-09-04 16:17:26 -04002148 called ``options``, now in the :mod:`argparse` context is called ``args``.
2149
2150* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
R. David Murray0f6b9d22017-09-06 20:25:40 -04002151 by using :meth:`~ArgumentParser.parse_intermixed_args` instead of
2152 :meth:`~ArgumentParser.parse_args`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002153
2154* Replace callback actions and the ``callback_*`` keyword arguments with
2155 ``type`` or ``action`` arguments.
2156
2157* Replace string names for ``type`` keyword arguments with the corresponding
2158 type objects (e.g. int, float, complex, etc).
2159
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002160* Replace :class:`optparse.Values` with :class:`Namespace` and
2161 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
2162 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002163
2164* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03002165 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002166 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00002167
2168* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panterd21e0b52015-10-10 10:36:22 +00002169 ``parser.add_argument('--version', action='version', version='<the version>')``.