blob: f8e39189686208fa896d8922b1a1e89576fba8d5 [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
60 optional arguments:
61 -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
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300151 * prog_ - The name of the program (default: ``sys.argv[0]``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000152
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300153 * usage_ - The string describing the program usage (default: generated from
154 arguments added to parser)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000155
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300156 * description_ - Text to display before the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000157
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300158 * epilog_ - Text to display after the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000159
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000160 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300161 also be included
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000162
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300163 * formatter_class_ - A class for customizing the help output
164
165 * prefix_chars_ - The set of characters that prefix optional arguments
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000166 (default: '-')
167
168 * fromfile_prefix_chars_ - The set of characters that prefix files from
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300169 which additional arguments should be read (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000170
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300171 * argument_default_ - The global default value for arguments
172 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000173
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300174 * conflict_handler_ - The strategy for resolving conflicting optionals
175 (usually unnecessary)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000176
Martin Panter536d70e2017-01-14 08:23:08 +0000177 * add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000178
Berker Peksag8089cd62015-02-14 01:39:17 +0200179 * allow_abbrev_ - Allows long options to be abbreviated if the
180 abbreviation is unambiguous. (default: ``True``)
181
Hai Shif5456382019-09-12 05:56:05 -0500182 * exit_on_error_ - Determines whether or not ArgumentParser exits with
183 error info when an error occurs. (default: ``True``)
184
Berker Peksag8089cd62015-02-14 01:39:17 +0200185 .. versionchanged:: 3.5
186 *allow_abbrev* parameter was added.
187
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500188 .. versionchanged:: 3.8
189 In previous versions, *allow_abbrev* also disabled grouping of short
190 flags such as ``-vv`` to mean ``-v -v``.
191
Hai Shif5456382019-09-12 05:56:05 -0500192 .. versionchanged:: 3.9
193 *exit_on_error* parameter was added.
194
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000195The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000196
197
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300198prog
199^^^^
200
Martin Panter0f0eac42016-09-07 11:04:41 +0000201By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300202how to display the name of the program in help messages. This default is almost
203always desirable because it will make the help messages match how the program was
204invoked on the command line. For example, consider a file named
205``myprogram.py`` with the following code::
206
207 import argparse
208 parser = argparse.ArgumentParser()
209 parser.add_argument('--foo', help='foo help')
210 args = parser.parse_args()
211
212The help for this program will display ``myprogram.py`` as the program name
Martin Panter1050d2d2016-07-26 11:18:21 +0200213(regardless of where the program was invoked from):
214
215.. code-block:: shell-session
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300216
217 $ python myprogram.py --help
218 usage: myprogram.py [-h] [--foo FOO]
219
220 optional arguments:
221 -h, --help show this help message and exit
222 --foo FOO foo help
223 $ cd ..
Martin Panter536d70e2017-01-14 08:23:08 +0000224 $ python subdir/myprogram.py --help
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300225 usage: myprogram.py [-h] [--foo FOO]
226
227 optional arguments:
228 -h, --help show this help message and exit
229 --foo FOO foo help
230
231To change this default behavior, another value can be supplied using the
232``prog=`` argument to :class:`ArgumentParser`::
233
234 >>> parser = argparse.ArgumentParser(prog='myprogram')
235 >>> parser.print_help()
236 usage: myprogram [-h]
237
238 optional arguments:
239 -h, --help show this help message and exit
240
241Note that the program name, whether determined from ``sys.argv[0]`` or from the
242``prog=`` argument, is available to help messages using the ``%(prog)s`` format
243specifier.
244
245::
246
247 >>> parser = argparse.ArgumentParser(prog='myprogram')
248 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
249 >>> parser.print_help()
250 usage: myprogram [-h] [--foo FOO]
251
252 optional arguments:
253 -h, --help show this help message and exit
254 --foo FOO foo of the myprogram program
255
256
257usage
258^^^^^
259
260By default, :class:`ArgumentParser` calculates the usage message from the
261arguments it contains::
262
263 >>> parser = argparse.ArgumentParser(prog='PROG')
264 >>> parser.add_argument('--foo', nargs='?', help='foo help')
265 >>> parser.add_argument('bar', nargs='+', help='bar help')
266 >>> parser.print_help()
267 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
268
269 positional arguments:
270 bar bar help
271
272 optional arguments:
273 -h, --help show this help message and exit
274 --foo [FOO] foo help
275
276The default message can be overridden with the ``usage=`` keyword argument::
277
278 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
279 >>> parser.add_argument('--foo', nargs='?', help='foo help')
280 >>> parser.add_argument('bar', nargs='+', help='bar help')
281 >>> parser.print_help()
282 usage: PROG [options]
283
284 positional arguments:
285 bar bar help
286
287 optional arguments:
288 -h, --help show this help message and exit
289 --foo [FOO] foo help
290
291The ``%(prog)s`` format specifier is available to fill in the program name in
292your usage messages.
293
294
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000295description
296^^^^^^^^^^^
297
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000298Most calls to the :class:`ArgumentParser` constructor will use the
299``description=`` keyword argument. This argument gives a brief description of
300what the program does and how it works. In help messages, the description is
301displayed between the command-line usage string and the help messages for the
302various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000303
304 >>> parser = argparse.ArgumentParser(description='A foo that bars')
305 >>> parser.print_help()
306 usage: argparse.py [-h]
307
308 A foo that bars
309
310 optional arguments:
311 -h, --help show this help message and exit
312
313By default, the description will be line-wrapped so that it fits within the
314given space. To change this behavior, see the formatter_class_ argument.
315
316
317epilog
318^^^^^^
319
320Some programs like to display additional description of the program after the
321description of the arguments. Such text can be specified using the ``epilog=``
322argument to :class:`ArgumentParser`::
323
324 >>> parser = argparse.ArgumentParser(
325 ... description='A foo that bars',
326 ... epilog="And that's how you'd foo a bar")
327 >>> parser.print_help()
328 usage: argparse.py [-h]
329
330 A foo that bars
331
332 optional arguments:
333 -h, --help show this help message and exit
334
335 And that's how you'd foo a bar
336
337As with the description_ argument, the ``epilog=`` text is by default
338line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000339argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000340
341
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000342parents
343^^^^^^^
344
345Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000346repeating the definitions of these arguments, a single parser with all the
347shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
348can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
349objects, collects all the positional and optional actions from them, and adds
350these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000351
352 >>> parent_parser = argparse.ArgumentParser(add_help=False)
353 >>> parent_parser.add_argument('--parent', type=int)
354
355 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
356 >>> foo_parser.add_argument('foo')
357 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
358 Namespace(foo='XXX', parent=2)
359
360 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
361 >>> bar_parser.add_argument('--bar')
362 >>> bar_parser.parse_args(['--bar', 'YYY'])
363 Namespace(bar='YYY', parent=None)
364
365Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000366:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
367and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000368
Steven Bethardd186f992011-03-26 21:49:00 +0100369.. note::
370 You must fully initialize the parsers before passing them via ``parents=``.
371 If you change the parent parsers after the child parser, those changes will
372 not be reflected in the child.
373
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000374
375formatter_class
376^^^^^^^^^^^^^^^
377
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000378:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300379specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300380classes:
381
382.. class:: RawDescriptionHelpFormatter
383 RawTextHelpFormatter
384 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300385 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000386
Steven Bethard0331e902011-03-26 14:48:04 +0100387:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
388more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000389By default, :class:`ArgumentParser` objects line-wrap the description_ and
390epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000391
392 >>> parser = argparse.ArgumentParser(
393 ... prog='PROG',
394 ... description='''this description
395 ... was indented weird
396 ... but that is okay''',
397 ... epilog='''
398 ... likewise for this epilog whose whitespace will
399 ... be cleaned up and whose words will be wrapped
400 ... across a couple lines''')
401 >>> parser.print_help()
402 usage: PROG [-h]
403
404 this description was indented weird but that is okay
405
406 optional arguments:
407 -h, --help show this help message and exit
408
409 likewise for this epilog whose whitespace will be cleaned up and whose words
410 will be wrapped across a couple lines
411
Steven Bethard0331e902011-03-26 14:48:04 +0100412Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000413indicates that description_ and epilog_ are already correctly formatted and
414should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000415
416 >>> parser = argparse.ArgumentParser(
417 ... prog='PROG',
418 ... formatter_class=argparse.RawDescriptionHelpFormatter,
419 ... description=textwrap.dedent('''\
420 ... Please do not mess up this text!
421 ... --------------------------------
422 ... I have indented it
423 ... exactly the way
424 ... I want it
425 ... '''))
426 >>> parser.print_help()
427 usage: PROG [-h]
428
429 Please do not mess up this text!
430 --------------------------------
431 I have indented it
432 exactly the way
433 I want it
434
435 optional arguments:
436 -h, --help show this help message and exit
437
Steven Bethard0331e902011-03-26 14:48:04 +0100438:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Elena Oat397c4672017-09-07 23:06:45 +0300439including argument descriptions. However, multiple new lines are replaced with
440one. If you wish to preserve multiple blank lines, add spaces between the
441newlines.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000442
Steven Bethard0331e902011-03-26 14:48:04 +0100443:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
444default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000445
446 >>> parser = argparse.ArgumentParser(
447 ... prog='PROG',
448 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
449 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
450 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
451 >>> parser.print_help()
Brandt Buchera0ed99b2019-11-11 12:47:48 -0800452 usage: PROG [-h] [--foo FOO] [bar ...]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000453
454 positional arguments:
455 bar BAR! (default: [1, 2, 3])
456
457 optional arguments:
458 -h, --help show this help message and exit
459 --foo FOO FOO! (default: 42)
460
Steven Bethard0331e902011-03-26 14:48:04 +0100461:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300462argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100463as the regular formatter does)::
464
465 >>> parser = argparse.ArgumentParser(
466 ... prog='PROG',
467 ... formatter_class=argparse.MetavarTypeHelpFormatter)
468 >>> parser.add_argument('--foo', type=int)
469 >>> parser.add_argument('bar', type=float)
470 >>> parser.print_help()
471 usage: PROG [-h] [--foo int] float
472
473 positional arguments:
474 float
475
476 optional arguments:
477 -h, --help show this help message and exit
478 --foo int
479
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000480
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300481prefix_chars
482^^^^^^^^^^^^
483
484Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
485Parsers that need to support different or additional prefix
486characters, e.g. for options
487like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
488to the ArgumentParser constructor::
489
490 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
491 >>> parser.add_argument('+f')
492 >>> parser.add_argument('++bar')
493 >>> parser.parse_args('+f X ++bar Y'.split())
494 Namespace(bar='Y', f='X')
495
496The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
497characters that does not include ``-`` will cause ``-f/--foo`` options to be
498disallowed.
499
500
501fromfile_prefix_chars
502^^^^^^^^^^^^^^^^^^^^^
503
504Sometimes, for example when dealing with a particularly long argument lists, it
505may make sense to keep the list of arguments in a file rather than typing it out
506at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
507:class:`ArgumentParser` constructor, then arguments that start with any of the
508specified characters will be treated as files, and will be replaced by the
509arguments they contain. For example::
510
511 >>> with open('args.txt', 'w') as fp:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300512 ... fp.write('-f\nbar')
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300513 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
514 >>> parser.add_argument('-f')
515 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
516 Namespace(f='bar')
517
518Arguments read from a file must by default be one per line (but see also
519:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
520were in the same place as the original file referencing argument on the command
521line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
522is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
523
524The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
525arguments will never be treated as file references.
526
527
528argument_default
529^^^^^^^^^^^^^^^^
530
531Generally, argument defaults are specified either by passing a default to
532:meth:`~ArgumentParser.add_argument` or by calling the
533:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
534pairs. Sometimes however, it may be useful to specify a single parser-wide
535default for arguments. This can be accomplished by passing the
536``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
537to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
538calls, we supply ``argument_default=SUPPRESS``::
539
540 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
541 >>> parser.add_argument('--foo')
542 >>> parser.add_argument('bar', nargs='?')
543 >>> parser.parse_args(['--foo', '1', 'BAR'])
544 Namespace(bar='BAR', foo='1')
545 >>> parser.parse_args([])
546 Namespace()
547
Berker Peksag8089cd62015-02-14 01:39:17 +0200548.. _allow_abbrev:
549
550allow_abbrev
551^^^^^^^^^^^^
552
553Normally, when you pass an argument list to the
Martin Panterd2ad5712015-11-02 04:20:33 +0000554:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`,
Berker Peksag8089cd62015-02-14 01:39:17 +0200555it :ref:`recognizes abbreviations <prefix-matching>` of long options.
556
557This feature can be disabled by setting ``allow_abbrev`` to ``False``::
558
559 >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
560 >>> parser.add_argument('--foobar', action='store_true')
561 >>> parser.add_argument('--foonley', action='store_false')
Berker Peksage7e497b2015-03-12 20:47:41 +0200562 >>> parser.parse_args(['--foon'])
Berker Peksag8089cd62015-02-14 01:39:17 +0200563 usage: PROG [-h] [--foobar] [--foonley]
564 PROG: error: unrecognized arguments: --foon
565
566.. versionadded:: 3.5
567
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300568
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000569conflict_handler
570^^^^^^^^^^^^^^^^
571
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000572:class:`ArgumentParser` objects do not allow two actions with the same option
Martin Panter0f0eac42016-09-07 11:04:41 +0000573string. By default, :class:`ArgumentParser` objects raise an exception if an
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000574attempt is made to create an argument with an option string that is already in
575use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000576
577 >>> parser = argparse.ArgumentParser(prog='PROG')
578 >>> parser.add_argument('-f', '--foo', help='old foo help')
579 >>> parser.add_argument('--foo', help='new foo help')
580 Traceback (most recent call last):
581 ..
582 ArgumentError: argument --foo: conflicting option string(s): --foo
583
584Sometimes (e.g. when using parents_) it may be useful to simply override any
585older arguments with the same option string. To get this behavior, the value
586``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000587:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000588
589 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
590 >>> parser.add_argument('-f', '--foo', help='old foo help')
591 >>> parser.add_argument('--foo', help='new foo help')
592 >>> parser.print_help()
593 usage: PROG [-h] [-f FOO] [--foo FOO]
594
595 optional arguments:
596 -h, --help show this help message and exit
597 -f FOO old foo help
598 --foo FOO new foo help
599
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000600Note that :class:`ArgumentParser` objects only remove an action if all of its
601option strings are overridden. So, in the example above, the old ``-f/--foo``
602action is retained as the ``-f`` action, because only the ``--foo`` option
603string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000604
605
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300606add_help
607^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000608
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300609By default, ArgumentParser objects add an option which simply displays
610the parser's help message. For example, consider a file named
611``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000612
613 import argparse
614 parser = argparse.ArgumentParser()
615 parser.add_argument('--foo', help='foo help')
616 args = parser.parse_args()
617
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300618If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Martin Panter1050d2d2016-07-26 11:18:21 +0200619help will be printed:
620
621.. code-block:: shell-session
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000622
623 $ python myprogram.py --help
624 usage: myprogram.py [-h] [--foo FOO]
625
626 optional arguments:
627 -h, --help show this help message and exit
628 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000629
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300630Occasionally, it may be useful to disable the addition of this help option.
631This can be achieved by passing ``False`` as the ``add_help=`` argument to
632:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000633
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300634 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
635 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000636 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300637 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000638
639 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300640 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000641
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300642The help option is typically ``-h/--help``. The exception to this is
643if the ``prefix_chars=`` is specified and does not include ``-``, in
644which case ``-h`` and ``--help`` are not valid options. In
645this case, the first character in ``prefix_chars`` is used to prefix
646the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000647
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300648 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000649 >>> parser.print_help()
Georg Brandld2914ce2013-10-06 09:50:36 +0200650 usage: PROG [+h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000651
652 optional arguments:
Georg Brandld2914ce2013-10-06 09:50:36 +0200653 +h, ++help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000654
655
Hai Shif5456382019-09-12 05:56:05 -0500656exit_on_error
657^^^^^^^^^^^^^
658
659Normally, when you pass an invalid argument list to the :meth:`~ArgumentParser.parse_args`
660method of an :class:`ArgumentParser`, it will exit with error info.
661
662If the user would like catch errors manually, the feature can be enable by setting
663``exit_on_error`` to ``False``::
664
665 >>> parser = argparse.ArgumentParser(exit_on_error=False)
666 >>> parser.add_argument('--integers', type=int)
667 _StoreAction(option_strings=['--integers'], dest='integers', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None)
668 >>> try:
669 ... parser.parse_args('--integers a'.split())
670 ... except argparse.ArgumentError:
671 ... print('Catching an argumentError')
672 ...
673 Catching an argumentError
674
675.. versionadded:: 3.9
676
677
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000678The add_argument() method
679-------------------------
680
Georg Brandlc9007082011-01-09 09:04:08 +0000681.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
682 [const], [default], [type], [choices], [required], \
683 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000684
Georg Brandl69518bc2011-04-16 16:44:54 +0200685 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000686 has its own more detailed description below, but in short they are:
687
688 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300689 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000690
691 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200692 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000693
694 * nargs_ - The number of command-line arguments that should be consumed.
695
696 * const_ - A constant value required by some action_ and nargs_ selections.
697
698 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200699 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000700
Ezio Melotti2409d772011-04-16 23:13:50 +0300701 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000702
703 * choices_ - A container of the allowable values for the argument.
704
705 * required_ - Whether or not the command-line option may be omitted
706 (optionals only).
707
708 * help_ - A brief description of what the argument does.
709
710 * metavar_ - A name for the argument in usage messages.
711
712 * dest_ - The name of the attribute to be added to the object returned by
713 :meth:`parse_args`.
714
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000715The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000716
Georg Brandle0bf91d2010-10-17 10:34:28 +0000717
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000718name or flags
719^^^^^^^^^^^^^
720
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300721The :meth:`~ArgumentParser.add_argument` method must know whether an optional
722argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
723filenames, is expected. The first arguments passed to
724:meth:`~ArgumentParser.add_argument` must therefore be either a series of
725flags, or a simple argument name. For example, an optional argument could
726be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000727
728 >>> parser.add_argument('-f', '--foo')
729
730while a positional argument could be created like::
731
732 >>> parser.add_argument('bar')
733
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300734When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
735identified by the ``-`` prefix, and the remaining arguments will be assumed to
736be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000737
738 >>> parser = argparse.ArgumentParser(prog='PROG')
739 >>> parser.add_argument('-f', '--foo')
740 >>> parser.add_argument('bar')
741 >>> parser.parse_args(['BAR'])
742 Namespace(bar='BAR', foo=None)
743 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
744 Namespace(bar='BAR', foo='FOO')
745 >>> parser.parse_args(['--foo', 'FOO'])
746 usage: PROG [-h] [-f FOO] bar
suic8604e82932018-04-11 20:45:04 +0200747 PROG: error: the following arguments are required: bar
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000748
Georg Brandle0bf91d2010-10-17 10:34:28 +0000749
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000750action
751^^^^^^
752
Éric Araujod9d7bca2011-08-10 04:19:03 +0200753:class:`ArgumentParser` objects associate command-line arguments with actions. These
754actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000755them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300756:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -0500757how the command-line arguments should be handled. The supplied actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000758
759* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300760 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000761
762 >>> parser = argparse.ArgumentParser()
763 >>> parser.add_argument('--foo')
764 >>> parser.parse_args('--foo 1'.split())
765 Namespace(foo='1')
766
767* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panterb4912b82016-04-09 03:49:48 +0000768 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300769 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000770
771 >>> parser = argparse.ArgumentParser()
772 >>> parser.add_argument('--foo', action='store_const', const=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000773 >>> parser.parse_args(['--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000774 Namespace(foo=42)
775
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800776* ``'store_true'`` and ``'store_false'`` - These are special cases of
777 ``'store_const'`` used for storing the values ``True`` and ``False``
778 respectively. In addition, they create default values of ``False`` and
779 ``True`` respectively. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000780
781 >>> parser = argparse.ArgumentParser()
782 >>> parser.add_argument('--foo', action='store_true')
783 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800784 >>> parser.add_argument('--baz', action='store_false')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000785 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800786 Namespace(foo=True, bar=False, baz=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000787
788* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000789 list. This is useful to allow an option to be specified multiple times.
790 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000791
792 >>> parser = argparse.ArgumentParser()
793 >>> parser.add_argument('--foo', action='append')
794 >>> parser.parse_args('--foo 1 --foo 2'.split())
795 Namespace(foo=['1', '2'])
796
797* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000798 the const_ keyword argument to the list. (Note that the const_ keyword
799 argument defaults to ``None``.) The ``'append_const'`` action is typically
800 useful when multiple arguments need to store constants to the same list. For
801 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000802
803 >>> parser = argparse.ArgumentParser()
804 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
805 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
806 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200807 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000808
Sandro Tosi98492a52012-01-04 23:25:04 +0100809* ``'count'`` - This counts the number of times a keyword argument occurs. For
810 example, this is useful for increasing verbosity levels::
811
812 >>> parser = argparse.ArgumentParser()
Raymond Hettinger04c79d62019-11-17 22:06:19 -0800813 >>> parser.add_argument('--verbose', '-v', action='count', default=0)
Martin Panterf5e60482016-04-26 11:41:25 +0000814 >>> parser.parse_args(['-vvv'])
Sandro Tosi98492a52012-01-04 23:25:04 +0100815 Namespace(verbose=3)
816
Raymond Hettinger04c79d62019-11-17 22:06:19 -0800817 Note, the *default* will be ``None`` unless explicitly set to *0*.
818
Sandro Tosi98492a52012-01-04 23:25:04 +0100819* ``'help'`` - This prints a complete help message for all the options in the
820 current parser and then exits. By default a help action is automatically
821 added to the parser. See :class:`ArgumentParser` for details of how the
822 output is created.
823
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000824* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300825 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100826 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000827
828 >>> import argparse
829 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000830 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
831 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000832 PROG 2.0
833
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +0300834* ``'extend'`` - This stores a list, and extends each argument value to the
835 list.
836 Example usage::
837
838 >>> parser = argparse.ArgumentParser()
839 >>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
840 >>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
841 Namespace(foo=['f1', 'f2', 'f3', 'f4'])
842
Batuhan Taşkaya74142072019-10-20 23:13:54 +0300843 .. versionadded:: 3.8
844
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400845You may also specify an arbitrary action by passing an Action subclass or
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200846other object that implements the same interface. The ``BooleanOptionalAction``
847is available in ``argparse`` and adds support for boolean actions such as
848``--foo`` and ``--no-foo``::
849
850 >>> import argparse
851 >>> parser = argparse.ArgumentParser()
852 >>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
853 >>> parser.parse_args(['--no-foo'])
854 Namespace(foo=False)
855
856The recommended way to create a custom action is to extend :class:`Action`,
857overriding the ``__call__`` method and optionally the ``__init__`` and
858``format_usage`` methods.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000859
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000860An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000861
862 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400863 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
864 ... if nargs is not None:
865 ... raise ValueError("nargs not allowed")
866 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000867 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000868 ... print('%r %r %r' % (namespace, values, option_string))
869 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000870 ...
871 >>> parser = argparse.ArgumentParser()
872 >>> parser.add_argument('--foo', action=FooAction)
873 >>> parser.add_argument('bar', action=FooAction)
874 >>> args = parser.parse_args('1 --foo 2'.split())
875 Namespace(bar=None, foo=None) '1' None
876 Namespace(bar='1', foo=None) '2' '--foo'
877 >>> args
878 Namespace(bar='1', foo='2')
879
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400880For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000881
882nargs
883^^^^^
884
885ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000886single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300887different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000888values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000889
Éric Araujoc3ef0372012-02-20 01:44:55 +0100890* ``N`` (an integer). ``N`` arguments from the command line will be gathered
891 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000892
Georg Brandl682d7e02010-10-06 10:26:05 +0000893 >>> parser = argparse.ArgumentParser()
894 >>> parser.add_argument('--foo', nargs=2)
895 >>> parser.add_argument('bar', nargs=1)
896 >>> parser.parse_args('c --foo a b'.split())
897 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000898
Georg Brandl682d7e02010-10-06 10:26:05 +0000899 Note that ``nargs=1`` produces a list of one item. This is different from
900 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000901
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200902.. index:: single: ? (question mark); in argparse module
903
Éric Araujofde92422011-08-19 01:30:26 +0200904* ``'?'``. One argument will be consumed from the command line if possible, and
905 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000906 default_ will be produced. Note that for optional arguments, there is an
907 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200908 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000909 examples to illustrate this::
910
911 >>> parser = argparse.ArgumentParser()
912 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
913 >>> parser.add_argument('bar', nargs='?', default='d')
Martin Panterf5e60482016-04-26 11:41:25 +0000914 >>> parser.parse_args(['XX', '--foo', 'YY'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000915 Namespace(bar='XX', foo='YY')
Martin Panterf5e60482016-04-26 11:41:25 +0000916 >>> parser.parse_args(['XX', '--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000917 Namespace(bar='XX', foo='c')
Martin Panterf5e60482016-04-26 11:41:25 +0000918 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000919 Namespace(bar='d', foo='d')
920
921 One of the more common uses of ``nargs='?'`` is to allow optional input and
922 output files::
923
924 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000925 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
926 ... default=sys.stdin)
927 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
928 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000929 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000930 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
931 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000932 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000933 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
934 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000935
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200936.. index:: single: * (asterisk); in argparse module
937
Éric Araujod9d7bca2011-08-10 04:19:03 +0200938* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000939 it generally doesn't make much sense to have more than one positional argument
940 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
941 possible. For example::
942
943 >>> parser = argparse.ArgumentParser()
944 >>> parser.add_argument('--foo', nargs='*')
945 >>> parser.add_argument('--bar', nargs='*')
946 >>> parser.add_argument('baz', nargs='*')
947 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
948 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
949
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200950.. index:: single: + (plus); in argparse module
951
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000952* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
953 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200954 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000955
956 >>> parser = argparse.ArgumentParser(prog='PROG')
957 >>> parser.add_argument('foo', nargs='+')
Martin Panterf5e60482016-04-26 11:41:25 +0000958 >>> parser.parse_args(['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000959 Namespace(foo=['a', 'b'])
Martin Panterf5e60482016-04-26 11:41:25 +0000960 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000961 usage: PROG [-h] foo [foo ...]
suic8604e82932018-04-11 20:45:04 +0200962 PROG: error: the following arguments are required: foo
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000963
R. David Murray0c7983e2017-09-04 16:17:26 -0400964.. _`argparse.REMAINDER`:
965
Sandro Tosida8e11a2012-01-19 22:23:00 +0100966* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
967 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100968 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100969
970 >>> parser = argparse.ArgumentParser(prog='PROG')
971 >>> parser.add_argument('--foo')
972 >>> parser.add_argument('command')
973 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100974 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100975 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100976
Éric Araujod9d7bca2011-08-10 04:19:03 +0200977If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200978is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000979will be consumed and a single item (not a list) will be produced.
980
981
982const
983^^^^^
984
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300985The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
986constant values that are not read from the command line but are required for
987the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000988
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300989* When :meth:`~ArgumentParser.add_argument` is called with
990 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100991 ``const`` value to one of the attributes of the object returned by
992 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000993
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300994* When :meth:`~ArgumentParser.add_argument` is called with option strings
995 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200996 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300997 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200998 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300999 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001000
Martin Panterb4912b82016-04-09 03:49:48 +00001001With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panter119e5022016-04-16 09:28:57 +00001002keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001003
1004
1005default
1006^^^^^^^
1007
1008All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001009command line. The ``default`` keyword argument of
1010:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +02001011specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001012For optional arguments, the ``default`` value is used when the option string
1013was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001014
1015 >>> parser = argparse.ArgumentParser()
1016 >>> parser.add_argument('--foo', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +00001017 >>> parser.parse_args(['--foo', '2'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001018 Namespace(foo='2')
Martin Panterf5e60482016-04-26 11:41:25 +00001019 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001020 Namespace(foo=42)
1021
Barry Warsaw1dedd0a2012-09-25 10:37:58 -04001022If the ``default`` value is a string, the parser parses the value as if it
1023were a command-line argument. In particular, the parser applies any type_
1024conversion argument, if provided, before setting the attribute on the
1025:class:`Namespace` return value. Otherwise, the parser uses the value as is::
1026
1027 >>> parser = argparse.ArgumentParser()
1028 >>> parser.add_argument('--length', default='10', type=int)
1029 >>> parser.add_argument('--width', default=10.5, type=int)
1030 >>> parser.parse_args()
1031 Namespace(length=10, width=10.5)
1032
Éric Araujo543edbd2011-08-19 01:45:12 +02001033For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +02001034is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001035
1036 >>> parser = argparse.ArgumentParser()
1037 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +00001038 >>> parser.parse_args(['a'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001039 Namespace(foo='a')
Martin Panterf5e60482016-04-26 11:41:25 +00001040 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001041 Namespace(foo=42)
1042
1043
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001044Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
Julien Palard78553132018-03-28 23:14:15 +02001045command-line argument was not present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001046
1047 >>> parser = argparse.ArgumentParser()
1048 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
1049 >>> parser.parse_args([])
1050 Namespace()
1051 >>> parser.parse_args(['--foo', '1'])
1052 Namespace(foo='1')
1053
1054
1055type
1056^^^^
1057
Éric Araujod9d7bca2011-08-10 04:19:03 +02001058By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001059strings. However, quite often the command-line string should instead be
1060interpreted as another type, like a :class:`float` or :class:`int`. The
1061``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +02001062necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001063types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001064
1065 >>> parser = argparse.ArgumentParser()
1066 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +00001067 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001068 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +00001069 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001070
Barry Warsaw1dedd0a2012-09-25 10:37:58 -04001071See the section on the default_ keyword argument for information on when the
1072``type`` argument is applied to default arguments.
1073
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001074To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001075factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
1076``errors=`` arguments of the :func:`open` function. For example,
1077``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001078
1079 >>> parser = argparse.ArgumentParser()
1080 >>> parser.add_argument('bar', type=argparse.FileType('w'))
1081 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +00001082 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001083
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001084``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +02001085the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001086
1087 >>> def perfect_square(string):
1088 ... value = int(string)
1089 ... sqrt = math.sqrt(value)
1090 ... if sqrt != int(sqrt):
1091 ... msg = "%r is not a perfect square" % string
1092 ... raise argparse.ArgumentTypeError(msg)
1093 ... return value
1094 ...
1095 >>> parser = argparse.ArgumentParser(prog='PROG')
1096 >>> parser.add_argument('foo', type=perfect_square)
Martin Panterf5e60482016-04-26 11:41:25 +00001097 >>> parser.parse_args(['9'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001098 Namespace(foo=9)
Martin Panterf5e60482016-04-26 11:41:25 +00001099 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001100 usage: PROG [-h] foo
1101 PROG: error: argument foo: '7' is not a perfect square
1102
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001103The choices_ keyword argument may be more convenient for type checkers that
1104simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001105
1106 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001107 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Martin Panterf5e60482016-04-26 11:41:25 +00001108 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001109 Namespace(foo=7)
Martin Panterf5e60482016-04-26 11:41:25 +00001110 >>> parser.parse_args(['11'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001111 usage: PROG [-h] {5,6,7,8,9}
1112 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1113
1114See the choices_ section for more details.
1115
1116
1117choices
1118^^^^^^^
1119
Éric Araujod9d7bca2011-08-10 04:19:03 +02001120Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001121These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001122argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001123parsed, argument values will be checked, and an error message will be displayed
1124if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001125
Chris Jerdonek174ef672013-01-11 19:26:44 -08001126 >>> parser = argparse.ArgumentParser(prog='game.py')
1127 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1128 >>> parser.parse_args(['rock'])
1129 Namespace(move='rock')
1130 >>> parser.parse_args(['fire'])
1131 usage: game.py [-h] {rock,paper,scissors}
1132 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1133 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001134
Chris Jerdonek174ef672013-01-11 19:26:44 -08001135Note that inclusion in the *choices* container is checked after any type_
1136conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001137container should match the type_ specified::
1138
Chris Jerdonek174ef672013-01-11 19:26:44 -08001139 >>> parser = argparse.ArgumentParser(prog='doors.py')
1140 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1141 >>> print(parser.parse_args(['3']))
1142 Namespace(door=3)
1143 >>> parser.parse_args(['4'])
1144 usage: doors.py [-h] {1,2,3}
1145 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001146
Raymond Hettinger84125fe2019-08-29 00:58:08 -07001147Any container can be passed as the *choices* value, so :class:`list` objects,
1148:class:`set` objects, and custom containers are all supported.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001149
1150
1151required
1152^^^^^^^^
1153
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001154In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001155indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001156To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001157keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001158
1159 >>> parser = argparse.ArgumentParser()
1160 >>> parser.add_argument('--foo', required=True)
1161 >>> parser.parse_args(['--foo', 'BAR'])
1162 Namespace(foo='BAR')
1163 >>> parser.parse_args([])
1164 usage: argparse.py [-h] [--foo FOO]
1165 argparse.py: error: option --foo is required
1166
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001167As the example shows, if an option is marked as ``required``,
1168:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1169present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001170
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001171.. note::
1172
1173 Required options are generally considered bad form because users expect
1174 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001175
1176
1177help
1178^^^^
1179
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001180The ``help`` value is a string containing a brief description of the argument.
1181When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001182command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001183argument::
1184
1185 >>> parser = argparse.ArgumentParser(prog='frobble')
1186 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001187 ... help='foo the bars before frobbling')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001188 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001189 ... help='one of the bars to be frobbled')
Martin Panterf5e60482016-04-26 11:41:25 +00001190 >>> parser.parse_args(['-h'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001191 usage: frobble [-h] [--foo] bar [bar ...]
1192
1193 positional arguments:
1194 bar one of the bars to be frobbled
1195
1196 optional arguments:
1197 -h, --help show this help message and exit
1198 --foo foo the bars before frobbling
1199
1200The ``help`` strings can include various format specifiers to avoid repetition
1201of things like the program name or the argument default_. The available
1202specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001203:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001204
1205 >>> parser = argparse.ArgumentParser(prog='frobble')
1206 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001207 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001208 >>> parser.print_help()
1209 usage: frobble [-h] [bar]
1210
1211 positional arguments:
1212 bar the bar to frobble (default: 42)
1213
1214 optional arguments:
1215 -h, --help show this help message and exit
1216
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001217As the help string supports %-formatting, if you want a literal ``%`` to appear
1218in the help string, you must escape it as ``%%``.
1219
Sandro Tosiea320ab2012-01-03 18:37:03 +01001220:mod:`argparse` supports silencing the help entry for certain options, by
1221setting the ``help`` value to ``argparse.SUPPRESS``::
1222
1223 >>> parser = argparse.ArgumentParser(prog='frobble')
1224 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1225 >>> parser.print_help()
1226 usage: frobble [-h]
1227
1228 optional arguments:
1229 -h, --help show this help message and exit
1230
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001231
1232metavar
1233^^^^^^^
1234
Sandro Tosi32587fb2013-01-11 10:49:00 +01001235When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001236to each expected argument. By default, ArgumentParser objects use the dest_
1237value as the "name" of each object. By default, for positional argument
1238actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001239the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001240``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001241optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001242will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001243
1244 >>> parser = argparse.ArgumentParser()
1245 >>> parser.add_argument('--foo')
1246 >>> parser.add_argument('bar')
1247 >>> parser.parse_args('X --foo Y'.split())
1248 Namespace(bar='X', foo='Y')
1249 >>> parser.print_help()
1250 usage: [-h] [--foo FOO] bar
1251
1252 positional arguments:
1253 bar
1254
1255 optional arguments:
1256 -h, --help show this help message and exit
1257 --foo FOO
1258
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001259An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001260
1261 >>> parser = argparse.ArgumentParser()
1262 >>> parser.add_argument('--foo', metavar='YYY')
1263 >>> parser.add_argument('bar', metavar='XXX')
1264 >>> parser.parse_args('X --foo Y'.split())
1265 Namespace(bar='X', foo='Y')
1266 >>> parser.print_help()
1267 usage: [-h] [--foo YYY] XXX
1268
1269 positional arguments:
1270 XXX
1271
1272 optional arguments:
1273 -h, --help show this help message and exit
1274 --foo YYY
1275
1276Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001277attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1278by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001279
1280Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001281Providing a tuple to ``metavar`` specifies a different display for each of the
1282arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001283
1284 >>> parser = argparse.ArgumentParser(prog='PROG')
1285 >>> parser.add_argument('-x', nargs=2)
1286 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1287 >>> parser.print_help()
1288 usage: PROG [-h] [-x X X] [--foo bar baz]
1289
1290 optional arguments:
1291 -h, --help show this help message and exit
1292 -x X X
1293 --foo bar baz
1294
1295
1296dest
1297^^^^
1298
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001299Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001300object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1301attribute is determined by the ``dest`` keyword argument of
1302:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1303``dest`` is normally supplied as the first argument to
1304:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001305
1306 >>> parser = argparse.ArgumentParser()
1307 >>> parser.add_argument('bar')
Martin Panterf5e60482016-04-26 11:41:25 +00001308 >>> parser.parse_args(['XXX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001309 Namespace(bar='XXX')
1310
1311For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001312the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001313taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001314string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001315the first short option string by stripping the initial ``-`` character. Any
1316internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001317the string is a valid attribute name. The examples below illustrate this
1318behavior::
1319
1320 >>> parser = argparse.ArgumentParser()
1321 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1322 >>> parser.add_argument('-x', '-y')
1323 >>> parser.parse_args('-f 1 -x 2'.split())
1324 Namespace(foo_bar='1', x='2')
1325 >>> parser.parse_args('--foo 1 -y 2'.split())
1326 Namespace(foo_bar='1', x='2')
1327
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001328``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001329
1330 >>> parser = argparse.ArgumentParser()
1331 >>> parser.add_argument('--foo', dest='bar')
1332 >>> parser.parse_args('--foo XXX'.split())
1333 Namespace(bar='XXX')
1334
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001335Action classes
1336^^^^^^^^^^^^^^
1337
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001338Action classes implement the Action API, a callable which returns a callable
1339which processes arguments from the command-line. Any object which follows
1340this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001341:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001342
Terry Jan Reedyee558262014-08-23 22:21:47 -04001343.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1344 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001345 metavar=None)
1346
1347Action objects are used by an ArgumentParser to represent the information
1348needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001349command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001350plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001351except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001352
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001353Instances of Action (or return value of any callable to the ``action``
1354parameter) should have attributes "dest", "option_strings", "default", "type",
1355"required", "help", etc. defined. The easiest way to ensure these attributes
1356are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001357
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001358Action instances should be callable, so subclasses must override the
1359``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001360
1361* ``parser`` - The ArgumentParser object which contains this action.
1362
1363* ``namespace`` - The :class:`Namespace` object that will be returned by
1364 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1365 object using :func:`setattr`.
1366
1367* ``values`` - The associated command-line arguments, with any type conversions
1368 applied. Type conversions are specified with the type_ keyword argument to
1369 :meth:`~ArgumentParser.add_argument`.
1370
1371* ``option_string`` - The option string that was used to invoke this action.
1372 The ``option_string`` argument is optional, and will be absent if the action
1373 is associated with a positional argument.
1374
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001375The ``__call__`` method may perform arbitrary actions, but will typically set
1376attributes on the ``namespace`` based on ``dest`` and ``values``.
1377
Rémi Lapeyre6a517c62019-09-13 12:17:43 +02001378Action subclasses can define a ``format_usage`` method that takes no argument
1379and return a string which will be used when printing the usage of the program.
1380If such method is not provided, a sensible default will be used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001381
1382The parse_args() method
1383-----------------------
1384
Georg Brandle0bf91d2010-10-17 10:34:28 +00001385.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001386
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001387 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001388 namespace. Return the populated namespace.
1389
1390 Previous calls to :meth:`add_argument` determine exactly what objects are
1391 created and how they are assigned. See the documentation for
1392 :meth:`add_argument` for details.
1393
R. David Murray0c7983e2017-09-04 16:17:26 -04001394 * args_ - List of strings to parse. The default is taken from
1395 :data:`sys.argv`.
1396
1397 * namespace_ - An object to take the attributes. The default is a new empty
1398 :class:`Namespace` object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001399
Georg Brandle0bf91d2010-10-17 10:34:28 +00001400
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001401Option value syntax
1402^^^^^^^^^^^^^^^^^^^
1403
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001404The :meth:`~ArgumentParser.parse_args` method supports several ways of
1405specifying the value of an option (if it takes one). In the simplest case, the
1406option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001407
1408 >>> parser = argparse.ArgumentParser(prog='PROG')
1409 >>> parser.add_argument('-x')
1410 >>> parser.add_argument('--foo')
Martin Panterf5e60482016-04-26 11:41:25 +00001411 >>> parser.parse_args(['-x', 'X'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001412 Namespace(foo=None, x='X')
Martin Panterf5e60482016-04-26 11:41:25 +00001413 >>> parser.parse_args(['--foo', 'FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001414 Namespace(foo='FOO', x=None)
1415
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001416For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001417and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001418separate them::
1419
Martin Panterf5e60482016-04-26 11:41:25 +00001420 >>> parser.parse_args(['--foo=FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001421 Namespace(foo='FOO', x=None)
1422
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001423For short options (options only one character long), the option and its value
1424can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001425
Martin Panterf5e60482016-04-26 11:41:25 +00001426 >>> parser.parse_args(['-xX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001427 Namespace(foo=None, x='X')
1428
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001429Several short options can be joined together, using only a single ``-`` prefix,
1430as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001431
1432 >>> parser = argparse.ArgumentParser(prog='PROG')
1433 >>> parser.add_argument('-x', action='store_true')
1434 >>> parser.add_argument('-y', action='store_true')
1435 >>> parser.add_argument('-z')
Martin Panterf5e60482016-04-26 11:41:25 +00001436 >>> parser.parse_args(['-xyzZ'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001437 Namespace(x=True, y=True, z='Z')
1438
1439
1440Invalid arguments
1441^^^^^^^^^^^^^^^^^
1442
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001443While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1444variety of errors, including ambiguous options, invalid types, invalid options,
1445wrong number of positional arguments, etc. When it encounters such an error,
1446it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001447
1448 >>> parser = argparse.ArgumentParser(prog='PROG')
1449 >>> parser.add_argument('--foo', type=int)
1450 >>> parser.add_argument('bar', nargs='?')
1451
1452 >>> # invalid type
1453 >>> parser.parse_args(['--foo', 'spam'])
1454 usage: PROG [-h] [--foo FOO] [bar]
1455 PROG: error: argument --foo: invalid int value: 'spam'
1456
1457 >>> # invalid option
1458 >>> parser.parse_args(['--bar'])
1459 usage: PROG [-h] [--foo FOO] [bar]
1460 PROG: error: no such option: --bar
1461
1462 >>> # wrong number of arguments
1463 >>> parser.parse_args(['spam', 'badger'])
1464 usage: PROG [-h] [--foo FOO] [bar]
1465 PROG: error: extra arguments found: badger
1466
1467
Éric Araujo543edbd2011-08-19 01:45:12 +02001468Arguments containing ``-``
1469^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001470
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001471The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1472the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001473ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001474attempt to specify an option or an attempt to provide a positional argument.
1475The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001476arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001477there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001478
1479 >>> parser = argparse.ArgumentParser(prog='PROG')
1480 >>> parser.add_argument('-x')
1481 >>> parser.add_argument('foo', nargs='?')
1482
1483 >>> # no negative number options, so -1 is a positional argument
1484 >>> parser.parse_args(['-x', '-1'])
1485 Namespace(foo=None, x='-1')
1486
1487 >>> # no negative number options, so -1 and -5 are positional arguments
1488 >>> parser.parse_args(['-x', '-1', '-5'])
1489 Namespace(foo='-5', x='-1')
1490
1491 >>> parser = argparse.ArgumentParser(prog='PROG')
1492 >>> parser.add_argument('-1', dest='one')
1493 >>> parser.add_argument('foo', nargs='?')
1494
1495 >>> # negative number options present, so -1 is an option
1496 >>> parser.parse_args(['-1', 'X'])
1497 Namespace(foo=None, one='X')
1498
1499 >>> # negative number options present, so -2 is an option
1500 >>> parser.parse_args(['-2'])
1501 usage: PROG [-h] [-1 ONE] [foo]
1502 PROG: error: no such option: -2
1503
1504 >>> # negative number options present, so both -1s are options
1505 >>> parser.parse_args(['-1', '-1'])
1506 usage: PROG [-h] [-1 ONE] [foo]
1507 PROG: error: argument -1: expected one argument
1508
Éric Araujo543edbd2011-08-19 01:45:12 +02001509If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001510like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001511:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1512argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001513
1514 >>> parser.parse_args(['--', '-f'])
1515 Namespace(foo='-f', one=None)
1516
Eli Benderskyf3114532013-12-02 05:49:54 -08001517.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001518
Eli Benderskyf3114532013-12-02 05:49:54 -08001519Argument abbreviations (prefix matching)
1520^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001521
Berker Peksag8089cd62015-02-14 01:39:17 +02001522The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>`
1523allows long options to be abbreviated to a prefix, if the abbreviation is
1524unambiguous (the prefix matches a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001525
1526 >>> parser = argparse.ArgumentParser(prog='PROG')
1527 >>> parser.add_argument('-bacon')
1528 >>> parser.add_argument('-badger')
1529 >>> parser.parse_args('-bac MMM'.split())
1530 Namespace(bacon='MMM', badger=None)
1531 >>> parser.parse_args('-bad WOOD'.split())
1532 Namespace(bacon=None, badger='WOOD')
1533 >>> parser.parse_args('-ba BA'.split())
1534 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1535 PROG: error: ambiguous option: -ba could match -badger, -bacon
1536
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001537An error is produced for arguments that could produce more than one options.
Berker Peksag8089cd62015-02-14 01:39:17 +02001538This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001539
R. David Murray0c7983e2017-09-04 16:17:26 -04001540.. _args:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001541
1542Beyond ``sys.argv``
1543^^^^^^^^^^^^^^^^^^^
1544
Éric Araujod9d7bca2011-08-10 04:19:03 +02001545Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001546of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001547:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1548interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001549
1550 >>> parser = argparse.ArgumentParser()
1551 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001552 ... 'integers', metavar='int', type=int, choices=range(10),
Serhiy Storchakadba90392016-05-10 12:01:23 +03001553 ... nargs='+', help='an integer in the range 0..9')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001554 >>> parser.add_argument(
1555 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001556 ... default=max, help='sum the integers (default: find the max)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001557 >>> parser.parse_args(['1', '2', '3', '4'])
1558 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panterf5e60482016-04-26 11:41:25 +00001559 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001560 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1561
R. David Murray0c7983e2017-09-04 16:17:26 -04001562.. _namespace:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001563
Steven Bethardd8f2d502011-03-26 19:50:06 +01001564The Namespace object
1565^^^^^^^^^^^^^^^^^^^^
1566
Éric Araujo63b18a42011-07-29 17:59:17 +02001567.. class:: Namespace
1568
1569 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1570 an object holding attributes and return it.
1571
1572This class is deliberately simple, just an :class:`object` subclass with a
1573readable string representation. If you prefer to have dict-like view of the
1574attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001575
1576 >>> parser = argparse.ArgumentParser()
1577 >>> parser.add_argument('--foo')
1578 >>> args = parser.parse_args(['--foo', 'BAR'])
1579 >>> vars(args)
1580 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001581
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001582It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001583already existing object, rather than a new :class:`Namespace` object. This can
1584be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001585
Éric Araujo28053fb2010-11-22 03:09:19 +00001586 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001587 ... pass
1588 ...
1589 >>> c = C()
1590 >>> parser = argparse.ArgumentParser()
1591 >>> parser.add_argument('--foo')
1592 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1593 >>> c.foo
1594 'BAR'
1595
1596
1597Other utilities
1598---------------
1599
1600Sub-commands
1601^^^^^^^^^^^^
1602
Georg Brandlfc9a1132013-10-06 18:51:39 +02001603.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1604 [parser_class], [action], \
Anthony Sottilecc182582018-08-23 20:08:54 -07001605 [option_string], [dest], [required], \
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001606 [help], [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001607
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001608 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001609 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001610 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001611 this way can be a particularly good idea when a program performs several
1612 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001613 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001614 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001615 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001616 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1617 command name and any :class:`ArgumentParser` constructor arguments, and
1618 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001619
Georg Brandlfc9a1132013-10-06 18:51:39 +02001620 Description of parameters:
1621
1622 * title - title for the sub-parser group in help output; by default
1623 "subcommands" if description is provided, otherwise uses title for
1624 positional arguments
1625
1626 * description - description for the sub-parser group in help output, by
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001627 default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001628
1629 * prog - usage information that will be displayed with sub-command help,
1630 by default the name of the program and any positional arguments before the
1631 subparser argument
1632
1633 * parser_class - class which will be used to create sub-parser instances, by
1634 default the class of the current parser (e.g. ArgumentParser)
1635
Berker Peksag5a494f62015-01-20 06:45:53 +02001636 * action_ - the basic type of action to be taken when this argument is
1637 encountered at the command line
1638
1639 * dest_ - name of the attribute under which sub-command name will be
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001640 stored; by default ``None`` and no value is stored
Georg Brandlfc9a1132013-10-06 18:51:39 +02001641
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001642 * required_ - Whether or not a subcommand must be provided, by default
Adam J. Stewart9e719172019-10-06 21:08:48 -05001643 ``False`` (added in 3.7)
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001644
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001645 * help_ - help for sub-parser group in help output, by default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001646
Berker Peksag5a494f62015-01-20 06:45:53 +02001647 * metavar_ - string presenting available sub-commands in help; by default it
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001648 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
Georg Brandlfc9a1132013-10-06 18:51:39 +02001649
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001650 Some example usage::
1651
1652 >>> # create the top-level parser
1653 >>> parser = argparse.ArgumentParser(prog='PROG')
1654 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1655 >>> subparsers = parser.add_subparsers(help='sub-command help')
1656 >>>
1657 >>> # create the parser for the "a" command
1658 >>> parser_a = subparsers.add_parser('a', help='a help')
1659 >>> parser_a.add_argument('bar', type=int, help='bar help')
1660 >>>
1661 >>> # create the parser for the "b" command
1662 >>> parser_b = subparsers.add_parser('b', help='b help')
1663 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1664 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001665 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001666 >>> parser.parse_args(['a', '12'])
1667 Namespace(bar=12, foo=False)
1668 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1669 Namespace(baz='Z', foo=True)
1670
1671 Note that the object returned by :meth:`parse_args` will only contain
1672 attributes for the main parser and the subparser that was selected by the
1673 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001674 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1675 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001676 ``baz`` attributes are present.
1677
1678 Similarly, when a help message is requested from a subparser, only the help
1679 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001680 include parent parser or sibling parser messages. (A help message for each
1681 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001682 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001683
1684 ::
1685
1686 >>> parser.parse_args(['--help'])
1687 usage: PROG [-h] [--foo] {a,b} ...
1688
1689 positional arguments:
1690 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001691 a a help
1692 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001693
1694 optional arguments:
1695 -h, --help show this help message and exit
1696 --foo foo help
1697
1698 >>> parser.parse_args(['a', '--help'])
1699 usage: PROG a [-h] bar
1700
1701 positional arguments:
1702 bar bar help
1703
1704 optional arguments:
1705 -h, --help show this help message and exit
1706
1707 >>> parser.parse_args(['b', '--help'])
1708 usage: PROG b [-h] [--baz {X,Y,Z}]
1709
1710 optional arguments:
1711 -h, --help show this help message and exit
1712 --baz {X,Y,Z} baz help
1713
1714 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1715 keyword arguments. When either is present, the subparser's commands will
1716 appear in their own group in the help output. For example::
1717
1718 >>> parser = argparse.ArgumentParser()
1719 >>> subparsers = parser.add_subparsers(title='subcommands',
1720 ... description='valid subcommands',
1721 ... help='additional help')
1722 >>> subparsers.add_parser('foo')
1723 >>> subparsers.add_parser('bar')
1724 >>> parser.parse_args(['-h'])
1725 usage: [-h] {foo,bar} ...
1726
1727 optional arguments:
1728 -h, --help show this help message and exit
1729
1730 subcommands:
1731 valid subcommands
1732
1733 {foo,bar} additional help
1734
Steven Bethardfd311a72010-12-18 11:19:23 +00001735 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1736 which allows multiple strings to refer to the same subparser. This example,
1737 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1738
1739 >>> parser = argparse.ArgumentParser()
1740 >>> subparsers = parser.add_subparsers()
1741 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1742 >>> checkout.add_argument('foo')
1743 >>> parser.parse_args(['co', 'bar'])
1744 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001745
1746 One particularly effective way of handling sub-commands is to combine the use
1747 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1748 that each subparser knows which Python function it should execute. For
1749 example::
1750
1751 >>> # sub-command functions
1752 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001753 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001754 ...
1755 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001756 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001757 ...
1758 >>> # create the top-level parser
1759 >>> parser = argparse.ArgumentParser()
1760 >>> subparsers = parser.add_subparsers()
1761 >>>
1762 >>> # create the parser for the "foo" command
1763 >>> parser_foo = subparsers.add_parser('foo')
1764 >>> parser_foo.add_argument('-x', type=int, default=1)
1765 >>> parser_foo.add_argument('y', type=float)
1766 >>> parser_foo.set_defaults(func=foo)
1767 >>>
1768 >>> # create the parser for the "bar" command
1769 >>> parser_bar = subparsers.add_parser('bar')
1770 >>> parser_bar.add_argument('z')
1771 >>> parser_bar.set_defaults(func=bar)
1772 >>>
1773 >>> # parse the args and call whatever function was selected
1774 >>> args = parser.parse_args('foo 1 -x 2'.split())
1775 >>> args.func(args)
1776 2.0
1777 >>>
1778 >>> # parse the args and call whatever function was selected
1779 >>> args = parser.parse_args('bar XYZYX'.split())
1780 >>> args.func(args)
1781 ((XYZYX))
1782
Steven Bethardfd311a72010-12-18 11:19:23 +00001783 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001784 appropriate function after argument parsing is complete. Associating
1785 functions with actions like this is typically the easiest way to handle the
1786 different actions for each of your subparsers. However, if it is necessary
1787 to check the name of the subparser that was invoked, the ``dest`` keyword
1788 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001789
1790 >>> parser = argparse.ArgumentParser()
1791 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1792 >>> subparser1 = subparsers.add_parser('1')
1793 >>> subparser1.add_argument('-x')
1794 >>> subparser2 = subparsers.add_parser('2')
1795 >>> subparser2.add_argument('y')
1796 >>> parser.parse_args(['2', 'frobble'])
1797 Namespace(subparser_name='2', y='frobble')
1798
Adam J. Stewart9e719172019-10-06 21:08:48 -05001799 .. versionchanged:: 3.7
1800 New *required* keyword argument.
1801
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001802
1803FileType objects
1804^^^^^^^^^^^^^^^^
1805
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001806.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001807
1808 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001809 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001810 :class:`FileType` objects as their type will open command-line arguments as
1811 files with the requested modes, buffer sizes, encodings and error handling
1812 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001813
Éric Araujoc3ef0372012-02-20 01:44:55 +01001814 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001815 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1816 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1817 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1818 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 +00001819
1820 FileType objects understand the pseudo-argument ``'-'`` and automatically
1821 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001822 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001823
Éric Araujoc3ef0372012-02-20 01:44:55 +01001824 >>> parser = argparse.ArgumentParser()
1825 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1826 >>> parser.parse_args(['-'])
1827 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001828
R David Murrayfced3ec2013-12-31 11:18:01 -05001829 .. versionadded:: 3.4
1830 The *encodings* and *errors* keyword arguments.
1831
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001832
1833Argument groups
1834^^^^^^^^^^^^^^^
1835
Georg Brandle0bf91d2010-10-17 10:34:28 +00001836.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001837
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001838 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001839 "positional arguments" and "optional arguments" when displaying help
1840 messages. When there is a better conceptual grouping of arguments than this
1841 default one, appropriate groups can be created using the
1842 :meth:`add_argument_group` method::
1843
1844 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1845 >>> group = parser.add_argument_group('group')
1846 >>> group.add_argument('--foo', help='foo help')
1847 >>> group.add_argument('bar', help='bar help')
1848 >>> parser.print_help()
1849 usage: PROG [--foo FOO] bar
1850
1851 group:
1852 bar bar help
1853 --foo FOO foo help
1854
1855 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001856 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1857 :class:`ArgumentParser`. When an argument is added to the group, the parser
1858 treats it just like a normal argument, but displays the argument in a
1859 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001860 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001861 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001862
1863 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1864 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1865 >>> group1.add_argument('foo', help='foo help')
1866 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1867 >>> group2.add_argument('--bar', help='bar help')
1868 >>> parser.print_help()
1869 usage: PROG [--bar BAR] foo
1870
1871 group1:
1872 group1 description
1873
1874 foo foo help
1875
1876 group2:
1877 group2 description
1878
1879 --bar BAR bar help
1880
Sandro Tosi99e7d072012-03-26 19:36:23 +02001881 Note that any arguments not in your user-defined groups will end up back
1882 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001883
1884
1885Mutual exclusion
1886^^^^^^^^^^^^^^^^
1887
Georg Brandled86ff82013-10-06 13:09:59 +02001888.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001889
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001890 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1891 one of the arguments in the mutually exclusive group was present on the
1892 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001893
1894 >>> parser = argparse.ArgumentParser(prog='PROG')
1895 >>> group = parser.add_mutually_exclusive_group()
1896 >>> group.add_argument('--foo', action='store_true')
1897 >>> group.add_argument('--bar', action='store_false')
1898 >>> parser.parse_args(['--foo'])
1899 Namespace(bar=True, foo=True)
1900 >>> parser.parse_args(['--bar'])
1901 Namespace(bar=False, foo=False)
1902 >>> parser.parse_args(['--foo', '--bar'])
1903 usage: PROG [-h] [--foo | --bar]
1904 PROG: error: argument --bar: not allowed with argument --foo
1905
Georg Brandle0bf91d2010-10-17 10:34:28 +00001906 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001907 argument, to indicate that at least one of the mutually exclusive arguments
1908 is required::
1909
1910 >>> parser = argparse.ArgumentParser(prog='PROG')
1911 >>> group = parser.add_mutually_exclusive_group(required=True)
1912 >>> group.add_argument('--foo', action='store_true')
1913 >>> group.add_argument('--bar', action='store_false')
1914 >>> parser.parse_args([])
1915 usage: PROG [-h] (--foo | --bar)
1916 PROG: error: one of the arguments --foo --bar is required
1917
1918 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001919 *title* and *description* arguments of
1920 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001921
1922
1923Parser defaults
1924^^^^^^^^^^^^^^^
1925
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001926.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001927
1928 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001929 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001930 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001931 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001932 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001933
1934 >>> parser = argparse.ArgumentParser()
1935 >>> parser.add_argument('foo', type=int)
1936 >>> parser.set_defaults(bar=42, baz='badger')
1937 >>> parser.parse_args(['736'])
1938 Namespace(bar=42, baz='badger', foo=736)
1939
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001940 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001941
1942 >>> parser = argparse.ArgumentParser()
1943 >>> parser.add_argument('--foo', default='bar')
1944 >>> parser.set_defaults(foo='spam')
1945 >>> parser.parse_args([])
1946 Namespace(foo='spam')
1947
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001948 Parser-level defaults can be particularly useful when working with multiple
1949 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1950 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001951
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001952.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001953
1954 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001955 :meth:`~ArgumentParser.add_argument` or by
1956 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001957
1958 >>> parser = argparse.ArgumentParser()
1959 >>> parser.add_argument('--foo', default='badger')
1960 >>> parser.get_default('foo')
1961 'badger'
1962
1963
1964Printing help
1965^^^^^^^^^^^^^
1966
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001967In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1968care of formatting and printing any usage or error messages. However, several
1969formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001970
Georg Brandle0bf91d2010-10-17 10:34:28 +00001971.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001972
1973 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001974 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001975 assumed.
1976
Georg Brandle0bf91d2010-10-17 10:34:28 +00001977.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001978
1979 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001980 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001981 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001982
1983There are also variants of these methods that simply return a string instead of
1984printing it:
1985
Georg Brandle0bf91d2010-10-17 10:34:28 +00001986.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001987
1988 Return a string containing a brief description of how the
1989 :class:`ArgumentParser` should be invoked on the command line.
1990
Georg Brandle0bf91d2010-10-17 10:34:28 +00001991.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001992
1993 Return a string containing a help message, including the program usage and
1994 information about the arguments registered with the :class:`ArgumentParser`.
1995
1996
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001997Partial parsing
1998^^^^^^^^^^^^^^^
1999
Georg Brandle0bf91d2010-10-17 10:34:28 +00002000.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002001
Georg Brandl69518bc2011-04-16 16:44:54 +02002002Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002003the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002004:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002005:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
2006extra arguments are present. Instead, it returns a two item tuple containing
2007the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002008
2009::
2010
2011 >>> parser = argparse.ArgumentParser()
2012 >>> parser.add_argument('--foo', action='store_true')
2013 >>> parser.add_argument('bar')
2014 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
2015 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
2016
Eli Benderskyf3114532013-12-02 05:49:54 -08002017.. warning::
2018 :ref:`Prefix matching <prefix-matching>` rules apply to
2019 :meth:`parse_known_args`. The parser may consume an option even if it's just
2020 a prefix of one of its known options, instead of leaving it in the remaining
2021 arguments list.
2022
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002023
2024Customizing file parsing
2025^^^^^^^^^^^^^^^^^^^^^^^^
2026
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002027.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002028
Georg Brandle0bf91d2010-10-17 10:34:28 +00002029 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002030 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft8b852f12014-05-20 12:58:38 -04002031 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002032 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002033
Georg Brandle0bf91d2010-10-17 10:34:28 +00002034 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002035 the argument file. It returns a list of arguments parsed from this string.
2036 The method is called once per line read from the argument file, in order.
2037
2038 A useful override of this method is one that treats each space-separated word
Berker Peksag5493e472016-10-17 06:14:17 +03002039 as an argument. The following example demonstrates how to do this::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002040
Berker Peksag5493e472016-10-17 06:14:17 +03002041 class MyArgumentParser(argparse.ArgumentParser):
2042 def convert_arg_line_to_args(self, arg_line):
2043 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002044
2045
Georg Brandl93754922010-10-17 10:28:04 +00002046Exiting methods
2047^^^^^^^^^^^^^^^
2048
2049.. method:: ArgumentParser.exit(status=0, message=None)
2050
2051 This method terminates the program, exiting with the specified *status*
Hai Shib1a2abd2019-09-12 10:34:24 -05002052 and, if given, it prints a *message* before that. The user can override
2053 this method to handle these steps differently::
2054
2055 class ErrorCatchingArgumentParser(argparse.ArgumentParser):
2056 def exit(self, status=0, message=None):
2057 if status:
2058 raise Exception(f'Exiting because of an error: {message}')
2059 exit(status)
Georg Brandl93754922010-10-17 10:28:04 +00002060
2061.. method:: ArgumentParser.error(message)
2062
2063 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08002064 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00002065
R. David Murray0f6b9d22017-09-06 20:25:40 -04002066
2067Intermixed parsing
2068^^^^^^^^^^^^^^^^^^
2069
2070.. method:: ArgumentParser.parse_intermixed_args(args=None, namespace=None)
2071.. method:: ArgumentParser.parse_known_intermixed_args(args=None, namespace=None)
2072
2073A number of Unix commands allow the user to intermix optional arguments with
2074positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args`
2075and :meth:`~ArgumentParser.parse_known_intermixed_args` methods
2076support this parsing style.
2077
2078These parsers do not support all the argparse features, and will raise
2079exceptions if unsupported features are used. In particular, subparsers,
2080``argparse.REMAINDER``, and mutually exclusive groups that include both
2081optionals and positionals are not supported.
2082
2083The following example shows the difference between
2084:meth:`~ArgumentParser.parse_known_args` and
2085:meth:`~ArgumentParser.parse_intermixed_args`: the former returns ``['2',
2086'3']`` as unparsed arguments, while the latter collects all the positionals
2087into ``rest``. ::
2088
2089 >>> parser = argparse.ArgumentParser()
2090 >>> parser.add_argument('--foo')
2091 >>> parser.add_argument('cmd')
2092 >>> parser.add_argument('rest', nargs='*', type=int)
2093 >>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
2094 (Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
2095 >>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
2096 Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])
2097
2098:meth:`~ArgumentParser.parse_known_intermixed_args` returns a two item tuple
2099containing the populated namespace and the list of remaining argument strings.
2100:meth:`~ArgumentParser.parse_intermixed_args` raises an error if there are any
2101remaining unparsed argument strings.
2102
2103.. versionadded:: 3.7
2104
Raymond Hettinger677e10a2010-12-07 06:45:30 +00002105.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00002106
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002107Upgrading optparse code
2108-----------------------
2109
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002110Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002111with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
2112transparently, particularly with the changes required to support the new
2113``nargs=`` specifiers and better usage messages. When most everything in
2114:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
2115longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002116
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03002117The :mod:`argparse` module improves on the standard library :mod:`optparse`
2118module in a number of ways including:
2119
2120* Handling positional arguments.
2121* Supporting sub-commands.
2122* Allowing alternative option prefixes like ``+`` and ``/``.
2123* Handling zero-or-more and one-or-more style arguments.
2124* Producing more informative usage messages.
2125* Providing a much simpler interface for custom ``type`` and ``action``.
2126
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002127A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002128
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002129* Replace all :meth:`optparse.OptionParser.add_option` calls with
2130 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002131
R David Murray5e0c5712012-03-30 18:07:42 -04002132* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00002133 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04002134 calls for the positional arguments. Keep in mind that what was previously
R. David Murray0c7983e2017-09-04 16:17:26 -04002135 called ``options``, now in the :mod:`argparse` context is called ``args``.
2136
2137* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
R. David Murray0f6b9d22017-09-06 20:25:40 -04002138 by using :meth:`~ArgumentParser.parse_intermixed_args` instead of
2139 :meth:`~ArgumentParser.parse_args`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002140
2141* Replace callback actions and the ``callback_*`` keyword arguments with
2142 ``type`` or ``action`` arguments.
2143
2144* Replace string names for ``type`` keyword arguments with the corresponding
2145 type objects (e.g. int, float, complex, etc).
2146
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002147* Replace :class:`optparse.Values` with :class:`Namespace` and
2148 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
2149 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002150
2151* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03002152 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002153 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00002154
2155* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panterd21e0b52015-10-10 10:36:22 +00002156 ``parser.add_argument('--version', action='version', version='<the version>')``.