blob: ef2fd42783c87722a0899cdabce0e28ccaf8ad27 [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', \
Berker Peksag8089cd62015-02-14 01:39:17 +0200145 add_help=True, allow_abbrev=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
182 .. versionchanged:: 3.5
183 *allow_abbrev* parameter was added.
184
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -0500185 .. versionchanged:: 3.8
186 In previous versions, *allow_abbrev* also disabled grouping of short
187 flags such as ``-vv`` to mean ``-v -v``.
188
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000189The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000190
191
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300192prog
193^^^^
194
Martin Panter0f0eac42016-09-07 11:04:41 +0000195By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300196how to display the name of the program in help messages. This default is almost
197always desirable because it will make the help messages match how the program was
198invoked on the command line. For example, consider a file named
199``myprogram.py`` with the following code::
200
201 import argparse
202 parser = argparse.ArgumentParser()
203 parser.add_argument('--foo', help='foo help')
204 args = parser.parse_args()
205
206The help for this program will display ``myprogram.py`` as the program name
Martin Panter1050d2d2016-07-26 11:18:21 +0200207(regardless of where the program was invoked from):
208
209.. code-block:: shell-session
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300210
211 $ python myprogram.py --help
212 usage: myprogram.py [-h] [--foo FOO]
213
214 optional arguments:
215 -h, --help show this help message and exit
216 --foo FOO foo help
217 $ cd ..
Martin Panter536d70e2017-01-14 08:23:08 +0000218 $ python subdir/myprogram.py --help
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300219 usage: myprogram.py [-h] [--foo FOO]
220
221 optional arguments:
222 -h, --help show this help message and exit
223 --foo FOO foo help
224
225To change this default behavior, another value can be supplied using the
226``prog=`` argument to :class:`ArgumentParser`::
227
228 >>> parser = argparse.ArgumentParser(prog='myprogram')
229 >>> parser.print_help()
230 usage: myprogram [-h]
231
232 optional arguments:
233 -h, --help show this help message and exit
234
235Note that the program name, whether determined from ``sys.argv[0]`` or from the
236``prog=`` argument, is available to help messages using the ``%(prog)s`` format
237specifier.
238
239::
240
241 >>> parser = argparse.ArgumentParser(prog='myprogram')
242 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
243 >>> parser.print_help()
244 usage: myprogram [-h] [--foo FOO]
245
246 optional arguments:
247 -h, --help show this help message and exit
248 --foo FOO foo of the myprogram program
249
250
251usage
252^^^^^
253
254By default, :class:`ArgumentParser` calculates the usage message from the
255arguments it contains::
256
257 >>> parser = argparse.ArgumentParser(prog='PROG')
258 >>> parser.add_argument('--foo', nargs='?', help='foo help')
259 >>> parser.add_argument('bar', nargs='+', help='bar help')
260 >>> parser.print_help()
261 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
262
263 positional arguments:
264 bar bar help
265
266 optional arguments:
267 -h, --help show this help message and exit
268 --foo [FOO] foo help
269
270The default message can be overridden with the ``usage=`` keyword argument::
271
272 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
273 >>> parser.add_argument('--foo', nargs='?', help='foo help')
274 >>> parser.add_argument('bar', nargs='+', help='bar help')
275 >>> parser.print_help()
276 usage: PROG [options]
277
278 positional arguments:
279 bar bar help
280
281 optional arguments:
282 -h, --help show this help message and exit
283 --foo [FOO] foo help
284
285The ``%(prog)s`` format specifier is available to fill in the program name in
286your usage messages.
287
288
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000289description
290^^^^^^^^^^^
291
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000292Most calls to the :class:`ArgumentParser` constructor will use the
293``description=`` keyword argument. This argument gives a brief description of
294what the program does and how it works. In help messages, the description is
295displayed between the command-line usage string and the help messages for the
296various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000297
298 >>> parser = argparse.ArgumentParser(description='A foo that bars')
299 >>> parser.print_help()
300 usage: argparse.py [-h]
301
302 A foo that bars
303
304 optional arguments:
305 -h, --help show this help message and exit
306
307By default, the description will be line-wrapped so that it fits within the
308given space. To change this behavior, see the formatter_class_ argument.
309
310
311epilog
312^^^^^^
313
314Some programs like to display additional description of the program after the
315description of the arguments. Such text can be specified using the ``epilog=``
316argument to :class:`ArgumentParser`::
317
318 >>> parser = argparse.ArgumentParser(
319 ... description='A foo that bars',
320 ... epilog="And that's how you'd foo a bar")
321 >>> parser.print_help()
322 usage: argparse.py [-h]
323
324 A foo that bars
325
326 optional arguments:
327 -h, --help show this help message and exit
328
329 And that's how you'd foo a bar
330
331As with the description_ argument, the ``epilog=`` text is by default
332line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000333argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000334
335
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000336parents
337^^^^^^^
338
339Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000340repeating the definitions of these arguments, a single parser with all the
341shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
342can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
343objects, collects all the positional and optional actions from them, and adds
344these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000345
346 >>> parent_parser = argparse.ArgumentParser(add_help=False)
347 >>> parent_parser.add_argument('--parent', type=int)
348
349 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
350 >>> foo_parser.add_argument('foo')
351 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
352 Namespace(foo='XXX', parent=2)
353
354 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
355 >>> bar_parser.add_argument('--bar')
356 >>> bar_parser.parse_args(['--bar', 'YYY'])
357 Namespace(bar='YYY', parent=None)
358
359Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000360:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
361and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000362
Steven Bethardd186f992011-03-26 21:49:00 +0100363.. note::
364 You must fully initialize the parsers before passing them via ``parents=``.
365 If you change the parent parsers after the child parser, those changes will
366 not be reflected in the child.
367
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000368
369formatter_class
370^^^^^^^^^^^^^^^
371
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000372:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300373specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300374classes:
375
376.. class:: RawDescriptionHelpFormatter
377 RawTextHelpFormatter
378 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300379 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000380
Steven Bethard0331e902011-03-26 14:48:04 +0100381:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
382more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000383By default, :class:`ArgumentParser` objects line-wrap the description_ and
384epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000385
386 >>> parser = argparse.ArgumentParser(
387 ... prog='PROG',
388 ... description='''this description
389 ... was indented weird
390 ... but that is okay''',
391 ... epilog='''
392 ... likewise for this epilog whose whitespace will
393 ... be cleaned up and whose words will be wrapped
394 ... across a couple lines''')
395 >>> parser.print_help()
396 usage: PROG [-h]
397
398 this description was indented weird but that is okay
399
400 optional arguments:
401 -h, --help show this help message and exit
402
403 likewise for this epilog whose whitespace will be cleaned up and whose words
404 will be wrapped across a couple lines
405
Steven Bethard0331e902011-03-26 14:48:04 +0100406Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000407indicates that description_ and epilog_ are already correctly formatted and
408should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000409
410 >>> parser = argparse.ArgumentParser(
411 ... prog='PROG',
412 ... formatter_class=argparse.RawDescriptionHelpFormatter,
413 ... description=textwrap.dedent('''\
414 ... Please do not mess up this text!
415 ... --------------------------------
416 ... I have indented it
417 ... exactly the way
418 ... I want it
419 ... '''))
420 >>> parser.print_help()
421 usage: PROG [-h]
422
423 Please do not mess up this text!
424 --------------------------------
425 I have indented it
426 exactly the way
427 I want it
428
429 optional arguments:
430 -h, --help show this help message and exit
431
Steven Bethard0331e902011-03-26 14:48:04 +0100432:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Elena Oat397c4672017-09-07 23:06:45 +0300433including argument descriptions. However, multiple new lines are replaced with
434one. If you wish to preserve multiple blank lines, add spaces between the
435newlines.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000436
Steven Bethard0331e902011-03-26 14:48:04 +0100437:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
438default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000439
440 >>> parser = argparse.ArgumentParser(
441 ... prog='PROG',
442 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
443 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
444 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
445 >>> parser.print_help()
446 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
447
448 positional arguments:
449 bar BAR! (default: [1, 2, 3])
450
451 optional arguments:
452 -h, --help show this help message and exit
453 --foo FOO FOO! (default: 42)
454
Steven Bethard0331e902011-03-26 14:48:04 +0100455:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300456argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100457as the regular formatter does)::
458
459 >>> parser = argparse.ArgumentParser(
460 ... prog='PROG',
461 ... formatter_class=argparse.MetavarTypeHelpFormatter)
462 >>> parser.add_argument('--foo', type=int)
463 >>> parser.add_argument('bar', type=float)
464 >>> parser.print_help()
465 usage: PROG [-h] [--foo int] float
466
467 positional arguments:
468 float
469
470 optional arguments:
471 -h, --help show this help message and exit
472 --foo int
473
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000474
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300475prefix_chars
476^^^^^^^^^^^^
477
478Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
479Parsers that need to support different or additional prefix
480characters, e.g. for options
481like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
482to the ArgumentParser constructor::
483
484 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
485 >>> parser.add_argument('+f')
486 >>> parser.add_argument('++bar')
487 >>> parser.parse_args('+f X ++bar Y'.split())
488 Namespace(bar='Y', f='X')
489
490The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
491characters that does not include ``-`` will cause ``-f/--foo`` options to be
492disallowed.
493
494
495fromfile_prefix_chars
496^^^^^^^^^^^^^^^^^^^^^
497
498Sometimes, for example when dealing with a particularly long argument lists, it
499may make sense to keep the list of arguments in a file rather than typing it out
500at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
501:class:`ArgumentParser` constructor, then arguments that start with any of the
502specified characters will be treated as files, and will be replaced by the
503arguments they contain. For example::
504
505 >>> with open('args.txt', 'w') as fp:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300506 ... fp.write('-f\nbar')
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300507 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
508 >>> parser.add_argument('-f')
509 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
510 Namespace(f='bar')
511
512Arguments read from a file must by default be one per line (but see also
513:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
514were in the same place as the original file referencing argument on the command
515line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
516is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
517
518The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
519arguments will never be treated as file references.
520
521
522argument_default
523^^^^^^^^^^^^^^^^
524
525Generally, argument defaults are specified either by passing a default to
526:meth:`~ArgumentParser.add_argument` or by calling the
527:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
528pairs. Sometimes however, it may be useful to specify a single parser-wide
529default for arguments. This can be accomplished by passing the
530``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
531to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
532calls, we supply ``argument_default=SUPPRESS``::
533
534 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
535 >>> parser.add_argument('--foo')
536 >>> parser.add_argument('bar', nargs='?')
537 >>> parser.parse_args(['--foo', '1', 'BAR'])
538 Namespace(bar='BAR', foo='1')
539 >>> parser.parse_args([])
540 Namespace()
541
Berker Peksag8089cd62015-02-14 01:39:17 +0200542.. _allow_abbrev:
543
544allow_abbrev
545^^^^^^^^^^^^
546
547Normally, when you pass an argument list to the
Martin Panterd2ad5712015-11-02 04:20:33 +0000548:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`,
Berker Peksag8089cd62015-02-14 01:39:17 +0200549it :ref:`recognizes abbreviations <prefix-matching>` of long options.
550
551This feature can be disabled by setting ``allow_abbrev`` to ``False``::
552
553 >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
554 >>> parser.add_argument('--foobar', action='store_true')
555 >>> parser.add_argument('--foonley', action='store_false')
Berker Peksage7e497b2015-03-12 20:47:41 +0200556 >>> parser.parse_args(['--foon'])
Berker Peksag8089cd62015-02-14 01:39:17 +0200557 usage: PROG [-h] [--foobar] [--foonley]
558 PROG: error: unrecognized arguments: --foon
559
560.. versionadded:: 3.5
561
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300562
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000563conflict_handler
564^^^^^^^^^^^^^^^^
565
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000566:class:`ArgumentParser` objects do not allow two actions with the same option
Martin Panter0f0eac42016-09-07 11:04:41 +0000567string. By default, :class:`ArgumentParser` objects raise an exception if an
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000568attempt is made to create an argument with an option string that is already in
569use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000570
571 >>> parser = argparse.ArgumentParser(prog='PROG')
572 >>> parser.add_argument('-f', '--foo', help='old foo help')
573 >>> parser.add_argument('--foo', help='new foo help')
574 Traceback (most recent call last):
575 ..
576 ArgumentError: argument --foo: conflicting option string(s): --foo
577
578Sometimes (e.g. when using parents_) it may be useful to simply override any
579older arguments with the same option string. To get this behavior, the value
580``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000581:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000582
583 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
584 >>> parser.add_argument('-f', '--foo', help='old foo help')
585 >>> parser.add_argument('--foo', help='new foo help')
586 >>> parser.print_help()
587 usage: PROG [-h] [-f FOO] [--foo FOO]
588
589 optional arguments:
590 -h, --help show this help message and exit
591 -f FOO old foo help
592 --foo FOO new foo help
593
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000594Note that :class:`ArgumentParser` objects only remove an action if all of its
595option strings are overridden. So, in the example above, the old ``-f/--foo``
596action is retained as the ``-f`` action, because only the ``--foo`` option
597string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000598
599
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300600add_help
601^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000602
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300603By default, ArgumentParser objects add an option which simply displays
604the parser's help message. For example, consider a file named
605``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000606
607 import argparse
608 parser = argparse.ArgumentParser()
609 parser.add_argument('--foo', help='foo help')
610 args = parser.parse_args()
611
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300612If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Martin Panter1050d2d2016-07-26 11:18:21 +0200613help will be printed:
614
615.. code-block:: shell-session
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000616
617 $ python myprogram.py --help
618 usage: myprogram.py [-h] [--foo FOO]
619
620 optional arguments:
621 -h, --help show this help message and exit
622 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000623
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300624Occasionally, it may be useful to disable the addition of this help option.
625This can be achieved by passing ``False`` as the ``add_help=`` argument to
626:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000627
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300628 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
629 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000630 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300631 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000632
633 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300634 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000635
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300636The help option is typically ``-h/--help``. The exception to this is
637if the ``prefix_chars=`` is specified and does not include ``-``, in
638which case ``-h`` and ``--help`` are not valid options. In
639this case, the first character in ``prefix_chars`` is used to prefix
640the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000641
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300642 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000643 >>> parser.print_help()
Georg Brandld2914ce2013-10-06 09:50:36 +0200644 usage: PROG [+h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000645
646 optional arguments:
Georg Brandld2914ce2013-10-06 09:50:36 +0200647 +h, ++help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000648
649
650The add_argument() method
651-------------------------
652
Georg Brandlc9007082011-01-09 09:04:08 +0000653.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
654 [const], [default], [type], [choices], [required], \
655 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000656
Georg Brandl69518bc2011-04-16 16:44:54 +0200657 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000658 has its own more detailed description below, but in short they are:
659
660 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300661 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000662
663 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200664 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000665
666 * nargs_ - The number of command-line arguments that should be consumed.
667
668 * const_ - A constant value required by some action_ and nargs_ selections.
669
670 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200671 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000672
Ezio Melotti2409d772011-04-16 23:13:50 +0300673 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000674
675 * choices_ - A container of the allowable values for the argument.
676
677 * required_ - Whether or not the command-line option may be omitted
678 (optionals only).
679
680 * help_ - A brief description of what the argument does.
681
682 * metavar_ - A name for the argument in usage messages.
683
684 * dest_ - The name of the attribute to be added to the object returned by
685 :meth:`parse_args`.
686
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000687The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000688
Georg Brandle0bf91d2010-10-17 10:34:28 +0000689
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000690name or flags
691^^^^^^^^^^^^^
692
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300693The :meth:`~ArgumentParser.add_argument` method must know whether an optional
694argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
695filenames, is expected. The first arguments passed to
696:meth:`~ArgumentParser.add_argument` must therefore be either a series of
697flags, or a simple argument name. For example, an optional argument could
698be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000699
700 >>> parser.add_argument('-f', '--foo')
701
702while a positional argument could be created like::
703
704 >>> parser.add_argument('bar')
705
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300706When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
707identified by the ``-`` prefix, and the remaining arguments will be assumed to
708be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000709
710 >>> parser = argparse.ArgumentParser(prog='PROG')
711 >>> parser.add_argument('-f', '--foo')
712 >>> parser.add_argument('bar')
713 >>> parser.parse_args(['BAR'])
714 Namespace(bar='BAR', foo=None)
715 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
716 Namespace(bar='BAR', foo='FOO')
717 >>> parser.parse_args(['--foo', 'FOO'])
718 usage: PROG [-h] [-f FOO] bar
suic8604e82932018-04-11 20:45:04 +0200719 PROG: error: the following arguments are required: bar
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000720
Georg Brandle0bf91d2010-10-17 10:34:28 +0000721
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000722action
723^^^^^^
724
Éric Araujod9d7bca2011-08-10 04:19:03 +0200725:class:`ArgumentParser` objects associate command-line arguments with actions. These
726actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000727them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300728:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -0500729how the command-line arguments should be handled. The supplied actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000730
731* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300732 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000733
734 >>> parser = argparse.ArgumentParser()
735 >>> parser.add_argument('--foo')
736 >>> parser.parse_args('--foo 1'.split())
737 Namespace(foo='1')
738
739* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panterb4912b82016-04-09 03:49:48 +0000740 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300741 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000742
743 >>> parser = argparse.ArgumentParser()
744 >>> parser.add_argument('--foo', action='store_const', const=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000745 >>> parser.parse_args(['--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000746 Namespace(foo=42)
747
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800748* ``'store_true'`` and ``'store_false'`` - These are special cases of
749 ``'store_const'`` used for storing the values ``True`` and ``False``
750 respectively. In addition, they create default values of ``False`` and
751 ``True`` respectively. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000752
753 >>> parser = argparse.ArgumentParser()
754 >>> parser.add_argument('--foo', action='store_true')
755 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800756 >>> parser.add_argument('--baz', action='store_false')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000757 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800758 Namespace(foo=True, bar=False, baz=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000759
760* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000761 list. This is useful to allow an option to be specified multiple times.
762 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000763
764 >>> parser = argparse.ArgumentParser()
765 >>> parser.add_argument('--foo', action='append')
766 >>> parser.parse_args('--foo 1 --foo 2'.split())
767 Namespace(foo=['1', '2'])
768
769* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000770 the const_ keyword argument to the list. (Note that the const_ keyword
771 argument defaults to ``None``.) The ``'append_const'`` action is typically
772 useful when multiple arguments need to store constants to the same list. For
773 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000774
775 >>> parser = argparse.ArgumentParser()
776 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
777 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
778 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200779 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000780
Sandro Tosi98492a52012-01-04 23:25:04 +0100781* ``'count'`` - This counts the number of times a keyword argument occurs. For
782 example, this is useful for increasing verbosity levels::
783
784 >>> parser = argparse.ArgumentParser()
785 >>> parser.add_argument('--verbose', '-v', action='count')
Martin Panterf5e60482016-04-26 11:41:25 +0000786 >>> parser.parse_args(['-vvv'])
Sandro Tosi98492a52012-01-04 23:25:04 +0100787 Namespace(verbose=3)
788
789* ``'help'`` - This prints a complete help message for all the options in the
790 current parser and then exits. By default a help action is automatically
791 added to the parser. See :class:`ArgumentParser` for details of how the
792 output is created.
793
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000794* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300795 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100796 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000797
798 >>> import argparse
799 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000800 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
801 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000802 PROG 2.0
803
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +0300804* ``'extend'`` - This stores a list, and extends each argument value to the
805 list.
806 Example usage::
807
808 >>> parser = argparse.ArgumentParser()
809 >>> parser.add_argument("--foo", action="extend", nargs="+", type=str)
810 >>> parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"])
811 Namespace(foo=['f1', 'f2', 'f3', 'f4'])
812
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400813You may also specify an arbitrary action by passing an Action subclass or
814other object that implements the same interface. The recommended way to do
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400815this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400816and optionally the ``__init__`` method.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000817
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000818An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000819
820 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400821 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
822 ... if nargs is not None:
823 ... raise ValueError("nargs not allowed")
824 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000825 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000826 ... print('%r %r %r' % (namespace, values, option_string))
827 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000828 ...
829 >>> parser = argparse.ArgumentParser()
830 >>> parser.add_argument('--foo', action=FooAction)
831 >>> parser.add_argument('bar', action=FooAction)
832 >>> args = parser.parse_args('1 --foo 2'.split())
833 Namespace(bar=None, foo=None) '1' None
834 Namespace(bar='1', foo=None) '2' '--foo'
835 >>> args
836 Namespace(bar='1', foo='2')
837
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400838For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000839
840nargs
841^^^^^
842
843ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000844single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300845different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000846values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000847
Éric Araujoc3ef0372012-02-20 01:44:55 +0100848* ``N`` (an integer). ``N`` arguments from the command line will be gathered
849 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000850
Georg Brandl682d7e02010-10-06 10:26:05 +0000851 >>> parser = argparse.ArgumentParser()
852 >>> parser.add_argument('--foo', nargs=2)
853 >>> parser.add_argument('bar', nargs=1)
854 >>> parser.parse_args('c --foo a b'.split())
855 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000856
Georg Brandl682d7e02010-10-06 10:26:05 +0000857 Note that ``nargs=1`` produces a list of one item. This is different from
858 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000859
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200860.. index:: single: ? (question mark); in argparse module
861
Éric Araujofde92422011-08-19 01:30:26 +0200862* ``'?'``. One argument will be consumed from the command line if possible, and
863 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000864 default_ will be produced. Note that for optional arguments, there is an
865 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200866 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000867 examples to illustrate this::
868
869 >>> parser = argparse.ArgumentParser()
870 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
871 >>> parser.add_argument('bar', nargs='?', default='d')
Martin Panterf5e60482016-04-26 11:41:25 +0000872 >>> parser.parse_args(['XX', '--foo', 'YY'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000873 Namespace(bar='XX', foo='YY')
Martin Panterf5e60482016-04-26 11:41:25 +0000874 >>> parser.parse_args(['XX', '--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000875 Namespace(bar='XX', foo='c')
Martin Panterf5e60482016-04-26 11:41:25 +0000876 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000877 Namespace(bar='d', foo='d')
878
879 One of the more common uses of ``nargs='?'`` is to allow optional input and
880 output files::
881
882 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000883 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
884 ... default=sys.stdin)
885 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
886 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000887 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000888 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
889 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000890 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000891 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
892 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000893
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200894.. index:: single: * (asterisk); in argparse module
895
Éric Araujod9d7bca2011-08-10 04:19:03 +0200896* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000897 it generally doesn't make much sense to have more than one positional argument
898 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
899 possible. For example::
900
901 >>> parser = argparse.ArgumentParser()
902 >>> parser.add_argument('--foo', nargs='*')
903 >>> parser.add_argument('--bar', nargs='*')
904 >>> parser.add_argument('baz', nargs='*')
905 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
906 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
907
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200908.. index:: single: + (plus); in argparse module
909
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000910* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
911 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200912 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000913
914 >>> parser = argparse.ArgumentParser(prog='PROG')
915 >>> parser.add_argument('foo', nargs='+')
Martin Panterf5e60482016-04-26 11:41:25 +0000916 >>> parser.parse_args(['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000917 Namespace(foo=['a', 'b'])
Martin Panterf5e60482016-04-26 11:41:25 +0000918 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000919 usage: PROG [-h] foo [foo ...]
suic8604e82932018-04-11 20:45:04 +0200920 PROG: error: the following arguments are required: foo
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000921
R. David Murray0c7983e2017-09-04 16:17:26 -0400922.. _`argparse.REMAINDER`:
923
Sandro Tosida8e11a2012-01-19 22:23:00 +0100924* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
925 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100926 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100927
928 >>> parser = argparse.ArgumentParser(prog='PROG')
929 >>> parser.add_argument('--foo')
930 >>> parser.add_argument('command')
931 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100932 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100933 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100934
Éric Araujod9d7bca2011-08-10 04:19:03 +0200935If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200936is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000937will be consumed and a single item (not a list) will be produced.
938
939
940const
941^^^^^
942
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300943The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
944constant values that are not read from the command line but are required for
945the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000946
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300947* When :meth:`~ArgumentParser.add_argument` is called with
948 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100949 ``const`` value to one of the attributes of the object returned by
950 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000951
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300952* When :meth:`~ArgumentParser.add_argument` is called with option strings
953 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200954 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300955 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200956 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300957 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000958
Martin Panterb4912b82016-04-09 03:49:48 +0000959With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panter119e5022016-04-16 09:28:57 +0000960keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000961
962
963default
964^^^^^^^
965
966All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300967command line. The ``default`` keyword argument of
968:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200969specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300970For optional arguments, the ``default`` value is used when the option string
971was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000972
973 >>> parser = argparse.ArgumentParser()
974 >>> parser.add_argument('--foo', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000975 >>> parser.parse_args(['--foo', '2'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000976 Namespace(foo='2')
Martin Panterf5e60482016-04-26 11:41:25 +0000977 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000978 Namespace(foo=42)
979
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400980If the ``default`` value is a string, the parser parses the value as if it
981were a command-line argument. In particular, the parser applies any type_
982conversion argument, if provided, before setting the attribute on the
983:class:`Namespace` return value. Otherwise, the parser uses the value as is::
984
985 >>> parser = argparse.ArgumentParser()
986 >>> parser.add_argument('--length', default='10', type=int)
987 >>> parser.add_argument('--width', default=10.5, type=int)
988 >>> parser.parse_args()
989 Namespace(length=10, width=10.5)
990
Éric Araujo543edbd2011-08-19 01:45:12 +0200991For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200992is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000993
994 >>> parser = argparse.ArgumentParser()
995 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000996 >>> parser.parse_args(['a'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000997 Namespace(foo='a')
Martin Panterf5e60482016-04-26 11:41:25 +0000998 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000999 Namespace(foo=42)
1000
1001
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001002Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
Julien Palard78553132018-03-28 23:14:15 +02001003command-line argument was not present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001004
1005 >>> parser = argparse.ArgumentParser()
1006 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
1007 >>> parser.parse_args([])
1008 Namespace()
1009 >>> parser.parse_args(['--foo', '1'])
1010 Namespace(foo='1')
1011
1012
1013type
1014^^^^
1015
Éric Araujod9d7bca2011-08-10 04:19:03 +02001016By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001017strings. However, quite often the command-line string should instead be
1018interpreted as another type, like a :class:`float` or :class:`int`. The
1019``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +02001020necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001021types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001022
1023 >>> parser = argparse.ArgumentParser()
1024 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +00001025 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001026 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +00001027 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001028
Barry Warsaw1dedd0a2012-09-25 10:37:58 -04001029See the section on the default_ keyword argument for information on when the
1030``type`` argument is applied to default arguments.
1031
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001032To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001033factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
1034``errors=`` arguments of the :func:`open` function. For example,
1035``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001036
1037 >>> parser = argparse.ArgumentParser()
1038 >>> parser.add_argument('bar', type=argparse.FileType('w'))
1039 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +00001040 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001041
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001042``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +02001043the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001044
1045 >>> def perfect_square(string):
1046 ... value = int(string)
1047 ... sqrt = math.sqrt(value)
1048 ... if sqrt != int(sqrt):
1049 ... msg = "%r is not a perfect square" % string
1050 ... raise argparse.ArgumentTypeError(msg)
1051 ... return value
1052 ...
1053 >>> parser = argparse.ArgumentParser(prog='PROG')
1054 >>> parser.add_argument('foo', type=perfect_square)
Martin Panterf5e60482016-04-26 11:41:25 +00001055 >>> parser.parse_args(['9'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001056 Namespace(foo=9)
Martin Panterf5e60482016-04-26 11:41:25 +00001057 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001058 usage: PROG [-h] foo
1059 PROG: error: argument foo: '7' is not a perfect square
1060
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001061The choices_ keyword argument may be more convenient for type checkers that
1062simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001063
1064 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001065 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Martin Panterf5e60482016-04-26 11:41:25 +00001066 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001067 Namespace(foo=7)
Martin Panterf5e60482016-04-26 11:41:25 +00001068 >>> parser.parse_args(['11'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001069 usage: PROG [-h] {5,6,7,8,9}
1070 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1071
1072See the choices_ section for more details.
1073
1074
1075choices
1076^^^^^^^
1077
Éric Araujod9d7bca2011-08-10 04:19:03 +02001078Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001079These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001080argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001081parsed, argument values will be checked, and an error message will be displayed
1082if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001083
Chris Jerdonek174ef672013-01-11 19:26:44 -08001084 >>> parser = argparse.ArgumentParser(prog='game.py')
1085 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1086 >>> parser.parse_args(['rock'])
1087 Namespace(move='rock')
1088 >>> parser.parse_args(['fire'])
1089 usage: game.py [-h] {rock,paper,scissors}
1090 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1091 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001092
Chris Jerdonek174ef672013-01-11 19:26:44 -08001093Note that inclusion in the *choices* container is checked after any type_
1094conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001095container should match the type_ specified::
1096
Chris Jerdonek174ef672013-01-11 19:26:44 -08001097 >>> parser = argparse.ArgumentParser(prog='doors.py')
1098 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1099 >>> print(parser.parse_args(['3']))
1100 Namespace(door=3)
1101 >>> parser.parse_args(['4'])
1102 usage: doors.py [-h] {1,2,3}
1103 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001104
Chris Jerdonek174ef672013-01-11 19:26:44 -08001105Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001106value, so :class:`dict` objects, :class:`set` objects, custom containers,
1107etc. are all supported.
1108
1109
1110required
1111^^^^^^^^
1112
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001113In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001114indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001115To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001116keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001117
1118 >>> parser = argparse.ArgumentParser()
1119 >>> parser.add_argument('--foo', required=True)
1120 >>> parser.parse_args(['--foo', 'BAR'])
1121 Namespace(foo='BAR')
1122 >>> parser.parse_args([])
1123 usage: argparse.py [-h] [--foo FOO]
1124 argparse.py: error: option --foo is required
1125
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001126As the example shows, if an option is marked as ``required``,
1127:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1128present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001129
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001130.. note::
1131
1132 Required options are generally considered bad form because users expect
1133 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001134
1135
1136help
1137^^^^
1138
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001139The ``help`` value is a string containing a brief description of the argument.
1140When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001141command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001142argument::
1143
1144 >>> parser = argparse.ArgumentParser(prog='frobble')
1145 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001146 ... help='foo the bars before frobbling')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001147 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001148 ... help='one of the bars to be frobbled')
Martin Panterf5e60482016-04-26 11:41:25 +00001149 >>> parser.parse_args(['-h'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001150 usage: frobble [-h] [--foo] bar [bar ...]
1151
1152 positional arguments:
1153 bar one of the bars to be frobbled
1154
1155 optional arguments:
1156 -h, --help show this help message and exit
1157 --foo foo the bars before frobbling
1158
1159The ``help`` strings can include various format specifiers to avoid repetition
1160of things like the program name or the argument default_. The available
1161specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001162:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001163
1164 >>> parser = argparse.ArgumentParser(prog='frobble')
1165 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001166 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001167 >>> parser.print_help()
1168 usage: frobble [-h] [bar]
1169
1170 positional arguments:
1171 bar the bar to frobble (default: 42)
1172
1173 optional arguments:
1174 -h, --help show this help message and exit
1175
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001176As the help string supports %-formatting, if you want a literal ``%`` to appear
1177in the help string, you must escape it as ``%%``.
1178
Sandro Tosiea320ab2012-01-03 18:37:03 +01001179:mod:`argparse` supports silencing the help entry for certain options, by
1180setting the ``help`` value to ``argparse.SUPPRESS``::
1181
1182 >>> parser = argparse.ArgumentParser(prog='frobble')
1183 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1184 >>> parser.print_help()
1185 usage: frobble [-h]
1186
1187 optional arguments:
1188 -h, --help show this help message and exit
1189
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001190
1191metavar
1192^^^^^^^
1193
Sandro Tosi32587fb2013-01-11 10:49:00 +01001194When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001195to each expected argument. By default, ArgumentParser objects use the dest_
1196value as the "name" of each object. By default, for positional argument
1197actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001198the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001199``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001200optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001201will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001202
1203 >>> parser = argparse.ArgumentParser()
1204 >>> parser.add_argument('--foo')
1205 >>> parser.add_argument('bar')
1206 >>> parser.parse_args('X --foo Y'.split())
1207 Namespace(bar='X', foo='Y')
1208 >>> parser.print_help()
1209 usage: [-h] [--foo FOO] bar
1210
1211 positional arguments:
1212 bar
1213
1214 optional arguments:
1215 -h, --help show this help message and exit
1216 --foo FOO
1217
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001218An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001219
1220 >>> parser = argparse.ArgumentParser()
1221 >>> parser.add_argument('--foo', metavar='YYY')
1222 >>> parser.add_argument('bar', metavar='XXX')
1223 >>> parser.parse_args('X --foo Y'.split())
1224 Namespace(bar='X', foo='Y')
1225 >>> parser.print_help()
1226 usage: [-h] [--foo YYY] XXX
1227
1228 positional arguments:
1229 XXX
1230
1231 optional arguments:
1232 -h, --help show this help message and exit
1233 --foo YYY
1234
1235Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001236attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1237by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001238
1239Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001240Providing a tuple to ``metavar`` specifies a different display for each of the
1241arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001242
1243 >>> parser = argparse.ArgumentParser(prog='PROG')
1244 >>> parser.add_argument('-x', nargs=2)
1245 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1246 >>> parser.print_help()
1247 usage: PROG [-h] [-x X X] [--foo bar baz]
1248
1249 optional arguments:
1250 -h, --help show this help message and exit
1251 -x X X
1252 --foo bar baz
1253
1254
1255dest
1256^^^^
1257
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001258Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001259object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1260attribute is determined by the ``dest`` keyword argument of
1261:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1262``dest`` is normally supplied as the first argument to
1263:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001264
1265 >>> parser = argparse.ArgumentParser()
1266 >>> parser.add_argument('bar')
Martin Panterf5e60482016-04-26 11:41:25 +00001267 >>> parser.parse_args(['XXX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001268 Namespace(bar='XXX')
1269
1270For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001271the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001272taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001273string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001274the first short option string by stripping the initial ``-`` character. Any
1275internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001276the string is a valid attribute name. The examples below illustrate this
1277behavior::
1278
1279 >>> parser = argparse.ArgumentParser()
1280 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1281 >>> parser.add_argument('-x', '-y')
1282 >>> parser.parse_args('-f 1 -x 2'.split())
1283 Namespace(foo_bar='1', x='2')
1284 >>> parser.parse_args('--foo 1 -y 2'.split())
1285 Namespace(foo_bar='1', x='2')
1286
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001287``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001288
1289 >>> parser = argparse.ArgumentParser()
1290 >>> parser.add_argument('--foo', dest='bar')
1291 >>> parser.parse_args('--foo XXX'.split())
1292 Namespace(bar='XXX')
1293
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001294Action classes
1295^^^^^^^^^^^^^^
1296
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001297Action classes implement the Action API, a callable which returns a callable
1298which processes arguments from the command-line. Any object which follows
1299this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001300:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001301
Terry Jan Reedyee558262014-08-23 22:21:47 -04001302.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1303 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001304 metavar=None)
1305
1306Action objects are used by an ArgumentParser to represent the information
1307needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001308command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001309plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001310except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001311
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001312Instances of Action (or return value of any callable to the ``action``
1313parameter) should have attributes "dest", "option_strings", "default", "type",
1314"required", "help", etc. defined. The easiest way to ensure these attributes
1315are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001316
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001317Action instances should be callable, so subclasses must override the
1318``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001319
1320* ``parser`` - The ArgumentParser object which contains this action.
1321
1322* ``namespace`` - The :class:`Namespace` object that will be returned by
1323 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1324 object using :func:`setattr`.
1325
1326* ``values`` - The associated command-line arguments, with any type conversions
1327 applied. Type conversions are specified with the type_ keyword argument to
1328 :meth:`~ArgumentParser.add_argument`.
1329
1330* ``option_string`` - The option string that was used to invoke this action.
1331 The ``option_string`` argument is optional, and will be absent if the action
1332 is associated with a positional argument.
1333
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001334The ``__call__`` method may perform arbitrary actions, but will typically set
1335attributes on the ``namespace`` based on ``dest`` and ``values``.
1336
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001337
1338The parse_args() method
1339-----------------------
1340
Georg Brandle0bf91d2010-10-17 10:34:28 +00001341.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001342
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001343 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001344 namespace. Return the populated namespace.
1345
1346 Previous calls to :meth:`add_argument` determine exactly what objects are
1347 created and how they are assigned. See the documentation for
1348 :meth:`add_argument` for details.
1349
R. David Murray0c7983e2017-09-04 16:17:26 -04001350 * args_ - List of strings to parse. The default is taken from
1351 :data:`sys.argv`.
1352
1353 * namespace_ - An object to take the attributes. The default is a new empty
1354 :class:`Namespace` object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001355
Georg Brandle0bf91d2010-10-17 10:34:28 +00001356
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001357Option value syntax
1358^^^^^^^^^^^^^^^^^^^
1359
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001360The :meth:`~ArgumentParser.parse_args` method supports several ways of
1361specifying the value of an option (if it takes one). In the simplest case, the
1362option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001363
1364 >>> parser = argparse.ArgumentParser(prog='PROG')
1365 >>> parser.add_argument('-x')
1366 >>> parser.add_argument('--foo')
Martin Panterf5e60482016-04-26 11:41:25 +00001367 >>> parser.parse_args(['-x', 'X'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001368 Namespace(foo=None, x='X')
Martin Panterf5e60482016-04-26 11:41:25 +00001369 >>> parser.parse_args(['--foo', 'FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001370 Namespace(foo='FOO', x=None)
1371
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001372For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001373and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001374separate them::
1375
Martin Panterf5e60482016-04-26 11:41:25 +00001376 >>> parser.parse_args(['--foo=FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001377 Namespace(foo='FOO', x=None)
1378
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001379For short options (options only one character long), the option and its value
1380can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001381
Martin Panterf5e60482016-04-26 11:41:25 +00001382 >>> parser.parse_args(['-xX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001383 Namespace(foo=None, x='X')
1384
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001385Several short options can be joined together, using only a single ``-`` prefix,
1386as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001387
1388 >>> parser = argparse.ArgumentParser(prog='PROG')
1389 >>> parser.add_argument('-x', action='store_true')
1390 >>> parser.add_argument('-y', action='store_true')
1391 >>> parser.add_argument('-z')
Martin Panterf5e60482016-04-26 11:41:25 +00001392 >>> parser.parse_args(['-xyzZ'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001393 Namespace(x=True, y=True, z='Z')
1394
1395
1396Invalid arguments
1397^^^^^^^^^^^^^^^^^
1398
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001399While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1400variety of errors, including ambiguous options, invalid types, invalid options,
1401wrong number of positional arguments, etc. When it encounters such an error,
1402it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001403
1404 >>> parser = argparse.ArgumentParser(prog='PROG')
1405 >>> parser.add_argument('--foo', type=int)
1406 >>> parser.add_argument('bar', nargs='?')
1407
1408 >>> # invalid type
1409 >>> parser.parse_args(['--foo', 'spam'])
1410 usage: PROG [-h] [--foo FOO] [bar]
1411 PROG: error: argument --foo: invalid int value: 'spam'
1412
1413 >>> # invalid option
1414 >>> parser.parse_args(['--bar'])
1415 usage: PROG [-h] [--foo FOO] [bar]
1416 PROG: error: no such option: --bar
1417
1418 >>> # wrong number of arguments
1419 >>> parser.parse_args(['spam', 'badger'])
1420 usage: PROG [-h] [--foo FOO] [bar]
1421 PROG: error: extra arguments found: badger
1422
1423
Éric Araujo543edbd2011-08-19 01:45:12 +02001424Arguments containing ``-``
1425^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001426
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001427The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1428the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001429ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001430attempt to specify an option or an attempt to provide a positional argument.
1431The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001432arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001433there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001434
1435 >>> parser = argparse.ArgumentParser(prog='PROG')
1436 >>> parser.add_argument('-x')
1437 >>> parser.add_argument('foo', nargs='?')
1438
1439 >>> # no negative number options, so -1 is a positional argument
1440 >>> parser.parse_args(['-x', '-1'])
1441 Namespace(foo=None, x='-1')
1442
1443 >>> # no negative number options, so -1 and -5 are positional arguments
1444 >>> parser.parse_args(['-x', '-1', '-5'])
1445 Namespace(foo='-5', x='-1')
1446
1447 >>> parser = argparse.ArgumentParser(prog='PROG')
1448 >>> parser.add_argument('-1', dest='one')
1449 >>> parser.add_argument('foo', nargs='?')
1450
1451 >>> # negative number options present, so -1 is an option
1452 >>> parser.parse_args(['-1', 'X'])
1453 Namespace(foo=None, one='X')
1454
1455 >>> # negative number options present, so -2 is an option
1456 >>> parser.parse_args(['-2'])
1457 usage: PROG [-h] [-1 ONE] [foo]
1458 PROG: error: no such option: -2
1459
1460 >>> # negative number options present, so both -1s are options
1461 >>> parser.parse_args(['-1', '-1'])
1462 usage: PROG [-h] [-1 ONE] [foo]
1463 PROG: error: argument -1: expected one argument
1464
Éric Araujo543edbd2011-08-19 01:45:12 +02001465If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001466like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001467:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1468argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001469
1470 >>> parser.parse_args(['--', '-f'])
1471 Namespace(foo='-f', one=None)
1472
Eli Benderskyf3114532013-12-02 05:49:54 -08001473.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001474
Eli Benderskyf3114532013-12-02 05:49:54 -08001475Argument abbreviations (prefix matching)
1476^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001477
Berker Peksag8089cd62015-02-14 01:39:17 +02001478The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>`
1479allows long options to be abbreviated to a prefix, if the abbreviation is
1480unambiguous (the prefix matches a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001481
1482 >>> parser = argparse.ArgumentParser(prog='PROG')
1483 >>> parser.add_argument('-bacon')
1484 >>> parser.add_argument('-badger')
1485 >>> parser.parse_args('-bac MMM'.split())
1486 Namespace(bacon='MMM', badger=None)
1487 >>> parser.parse_args('-bad WOOD'.split())
1488 Namespace(bacon=None, badger='WOOD')
1489 >>> parser.parse_args('-ba BA'.split())
1490 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1491 PROG: error: ambiguous option: -ba could match -badger, -bacon
1492
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001493An error is produced for arguments that could produce more than one options.
Berker Peksag8089cd62015-02-14 01:39:17 +02001494This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001495
R. David Murray0c7983e2017-09-04 16:17:26 -04001496.. _args:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001497
1498Beyond ``sys.argv``
1499^^^^^^^^^^^^^^^^^^^
1500
Éric Araujod9d7bca2011-08-10 04:19:03 +02001501Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001502of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001503:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1504interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001505
1506 >>> parser = argparse.ArgumentParser()
1507 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001508 ... 'integers', metavar='int', type=int, choices=range(10),
Serhiy Storchakadba90392016-05-10 12:01:23 +03001509 ... nargs='+', help='an integer in the range 0..9')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001510 >>> parser.add_argument(
1511 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001512 ... default=max, help='sum the integers (default: find the max)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001513 >>> parser.parse_args(['1', '2', '3', '4'])
1514 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panterf5e60482016-04-26 11:41:25 +00001515 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001516 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1517
R. David Murray0c7983e2017-09-04 16:17:26 -04001518.. _namespace:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001519
Steven Bethardd8f2d502011-03-26 19:50:06 +01001520The Namespace object
1521^^^^^^^^^^^^^^^^^^^^
1522
Éric Araujo63b18a42011-07-29 17:59:17 +02001523.. class:: Namespace
1524
1525 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1526 an object holding attributes and return it.
1527
1528This class is deliberately simple, just an :class:`object` subclass with a
1529readable string representation. If you prefer to have dict-like view of the
1530attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001531
1532 >>> parser = argparse.ArgumentParser()
1533 >>> parser.add_argument('--foo')
1534 >>> args = parser.parse_args(['--foo', 'BAR'])
1535 >>> vars(args)
1536 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001537
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001538It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001539already existing object, rather than a new :class:`Namespace` object. This can
1540be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001541
Éric Araujo28053fb2010-11-22 03:09:19 +00001542 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001543 ... pass
1544 ...
1545 >>> c = C()
1546 >>> parser = argparse.ArgumentParser()
1547 >>> parser.add_argument('--foo')
1548 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1549 >>> c.foo
1550 'BAR'
1551
1552
1553Other utilities
1554---------------
1555
1556Sub-commands
1557^^^^^^^^^^^^
1558
Georg Brandlfc9a1132013-10-06 18:51:39 +02001559.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1560 [parser_class], [action], \
Anthony Sottilecc182582018-08-23 20:08:54 -07001561 [option_string], [dest], [required], \
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001562 [help], [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001563
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001564 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001565 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001566 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001567 this way can be a particularly good idea when a program performs several
1568 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001569 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001570 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001571 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001572 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1573 command name and any :class:`ArgumentParser` constructor arguments, and
1574 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001575
Georg Brandlfc9a1132013-10-06 18:51:39 +02001576 Description of parameters:
1577
1578 * title - title for the sub-parser group in help output; by default
1579 "subcommands" if description is provided, otherwise uses title for
1580 positional arguments
1581
1582 * description - description for the sub-parser group in help output, by
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001583 default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001584
1585 * prog - usage information that will be displayed with sub-command help,
1586 by default the name of the program and any positional arguments before the
1587 subparser argument
1588
1589 * parser_class - class which will be used to create sub-parser instances, by
1590 default the class of the current parser (e.g. ArgumentParser)
1591
Berker Peksag5a494f62015-01-20 06:45:53 +02001592 * action_ - the basic type of action to be taken when this argument is
1593 encountered at the command line
1594
1595 * dest_ - name of the attribute under which sub-command name will be
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001596 stored; by default ``None`` and no value is stored
Georg Brandlfc9a1132013-10-06 18:51:39 +02001597
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001598 * required_ - Whether or not a subcommand must be provided, by default
Ned Deily8ebf5ce2018-05-23 21:55:15 -04001599 ``False``.
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001600
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001601 * help_ - help for sub-parser group in help output, by default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001602
Berker Peksag5a494f62015-01-20 06:45:53 +02001603 * metavar_ - string presenting available sub-commands in help; by default it
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001604 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
Georg Brandlfc9a1132013-10-06 18:51:39 +02001605
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001606 Some example usage::
1607
1608 >>> # create the top-level parser
1609 >>> parser = argparse.ArgumentParser(prog='PROG')
1610 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1611 >>> subparsers = parser.add_subparsers(help='sub-command help')
1612 >>>
1613 >>> # create the parser for the "a" command
1614 >>> parser_a = subparsers.add_parser('a', help='a help')
1615 >>> parser_a.add_argument('bar', type=int, help='bar help')
1616 >>>
1617 >>> # create the parser for the "b" command
1618 >>> parser_b = subparsers.add_parser('b', help='b help')
1619 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1620 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001621 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001622 >>> parser.parse_args(['a', '12'])
1623 Namespace(bar=12, foo=False)
1624 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1625 Namespace(baz='Z', foo=True)
1626
1627 Note that the object returned by :meth:`parse_args` will only contain
1628 attributes for the main parser and the subparser that was selected by the
1629 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001630 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1631 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001632 ``baz`` attributes are present.
1633
1634 Similarly, when a help message is requested from a subparser, only the help
1635 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001636 include parent parser or sibling parser messages. (A help message for each
1637 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001638 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001639
1640 ::
1641
1642 >>> parser.parse_args(['--help'])
1643 usage: PROG [-h] [--foo] {a,b} ...
1644
1645 positional arguments:
1646 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001647 a a help
1648 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001649
1650 optional arguments:
1651 -h, --help show this help message and exit
1652 --foo foo help
1653
1654 >>> parser.parse_args(['a', '--help'])
1655 usage: PROG a [-h] bar
1656
1657 positional arguments:
1658 bar bar help
1659
1660 optional arguments:
1661 -h, --help show this help message and exit
1662
1663 >>> parser.parse_args(['b', '--help'])
1664 usage: PROG b [-h] [--baz {X,Y,Z}]
1665
1666 optional arguments:
1667 -h, --help show this help message and exit
1668 --baz {X,Y,Z} baz help
1669
1670 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1671 keyword arguments. When either is present, the subparser's commands will
1672 appear in their own group in the help output. For example::
1673
1674 >>> parser = argparse.ArgumentParser()
1675 >>> subparsers = parser.add_subparsers(title='subcommands',
1676 ... description='valid subcommands',
1677 ... help='additional help')
1678 >>> subparsers.add_parser('foo')
1679 >>> subparsers.add_parser('bar')
1680 >>> parser.parse_args(['-h'])
1681 usage: [-h] {foo,bar} ...
1682
1683 optional arguments:
1684 -h, --help show this help message and exit
1685
1686 subcommands:
1687 valid subcommands
1688
1689 {foo,bar} additional help
1690
Steven Bethardfd311a72010-12-18 11:19:23 +00001691 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1692 which allows multiple strings to refer to the same subparser. This example,
1693 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1694
1695 >>> parser = argparse.ArgumentParser()
1696 >>> subparsers = parser.add_subparsers()
1697 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1698 >>> checkout.add_argument('foo')
1699 >>> parser.parse_args(['co', 'bar'])
1700 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001701
1702 One particularly effective way of handling sub-commands is to combine the use
1703 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1704 that each subparser knows which Python function it should execute. For
1705 example::
1706
1707 >>> # sub-command functions
1708 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001709 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001710 ...
1711 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001712 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001713 ...
1714 >>> # create the top-level parser
1715 >>> parser = argparse.ArgumentParser()
1716 >>> subparsers = parser.add_subparsers()
1717 >>>
1718 >>> # create the parser for the "foo" command
1719 >>> parser_foo = subparsers.add_parser('foo')
1720 >>> parser_foo.add_argument('-x', type=int, default=1)
1721 >>> parser_foo.add_argument('y', type=float)
1722 >>> parser_foo.set_defaults(func=foo)
1723 >>>
1724 >>> # create the parser for the "bar" command
1725 >>> parser_bar = subparsers.add_parser('bar')
1726 >>> parser_bar.add_argument('z')
1727 >>> parser_bar.set_defaults(func=bar)
1728 >>>
1729 >>> # parse the args and call whatever function was selected
1730 >>> args = parser.parse_args('foo 1 -x 2'.split())
1731 >>> args.func(args)
1732 2.0
1733 >>>
1734 >>> # parse the args and call whatever function was selected
1735 >>> args = parser.parse_args('bar XYZYX'.split())
1736 >>> args.func(args)
1737 ((XYZYX))
1738
Steven Bethardfd311a72010-12-18 11:19:23 +00001739 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001740 appropriate function after argument parsing is complete. Associating
1741 functions with actions like this is typically the easiest way to handle the
1742 different actions for each of your subparsers. However, if it is necessary
1743 to check the name of the subparser that was invoked, the ``dest`` keyword
1744 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001745
1746 >>> parser = argparse.ArgumentParser()
1747 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1748 >>> subparser1 = subparsers.add_parser('1')
1749 >>> subparser1.add_argument('-x')
1750 >>> subparser2 = subparsers.add_parser('2')
1751 >>> subparser2.add_argument('y')
1752 >>> parser.parse_args(['2', 'frobble'])
1753 Namespace(subparser_name='2', y='frobble')
1754
1755
1756FileType objects
1757^^^^^^^^^^^^^^^^
1758
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001759.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001760
1761 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001762 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001763 :class:`FileType` objects as their type will open command-line arguments as
1764 files with the requested modes, buffer sizes, encodings and error handling
1765 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001766
Éric Araujoc3ef0372012-02-20 01:44:55 +01001767 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001768 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1769 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1770 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1771 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 +00001772
1773 FileType objects understand the pseudo-argument ``'-'`` and automatically
1774 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001775 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001776
Éric Araujoc3ef0372012-02-20 01:44:55 +01001777 >>> parser = argparse.ArgumentParser()
1778 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1779 >>> parser.parse_args(['-'])
1780 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001781
R David Murrayfced3ec2013-12-31 11:18:01 -05001782 .. versionadded:: 3.4
1783 The *encodings* and *errors* keyword arguments.
1784
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001785
1786Argument groups
1787^^^^^^^^^^^^^^^
1788
Georg Brandle0bf91d2010-10-17 10:34:28 +00001789.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001790
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001791 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001792 "positional arguments" and "optional arguments" when displaying help
1793 messages. When there is a better conceptual grouping of arguments than this
1794 default one, appropriate groups can be created using the
1795 :meth:`add_argument_group` method::
1796
1797 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1798 >>> group = parser.add_argument_group('group')
1799 >>> group.add_argument('--foo', help='foo help')
1800 >>> group.add_argument('bar', help='bar help')
1801 >>> parser.print_help()
1802 usage: PROG [--foo FOO] bar
1803
1804 group:
1805 bar bar help
1806 --foo FOO foo help
1807
1808 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001809 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1810 :class:`ArgumentParser`. When an argument is added to the group, the parser
1811 treats it just like a normal argument, but displays the argument in a
1812 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001813 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001814 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001815
1816 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1817 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1818 >>> group1.add_argument('foo', help='foo help')
1819 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1820 >>> group2.add_argument('--bar', help='bar help')
1821 >>> parser.print_help()
1822 usage: PROG [--bar BAR] foo
1823
1824 group1:
1825 group1 description
1826
1827 foo foo help
1828
1829 group2:
1830 group2 description
1831
1832 --bar BAR bar help
1833
Sandro Tosi99e7d072012-03-26 19:36:23 +02001834 Note that any arguments not in your user-defined groups will end up back
1835 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001836
1837
1838Mutual exclusion
1839^^^^^^^^^^^^^^^^
1840
Georg Brandled86ff82013-10-06 13:09:59 +02001841.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001842
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001843 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1844 one of the arguments in the mutually exclusive group was present on the
1845 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001846
1847 >>> parser = argparse.ArgumentParser(prog='PROG')
1848 >>> group = parser.add_mutually_exclusive_group()
1849 >>> group.add_argument('--foo', action='store_true')
1850 >>> group.add_argument('--bar', action='store_false')
1851 >>> parser.parse_args(['--foo'])
1852 Namespace(bar=True, foo=True)
1853 >>> parser.parse_args(['--bar'])
1854 Namespace(bar=False, foo=False)
1855 >>> parser.parse_args(['--foo', '--bar'])
1856 usage: PROG [-h] [--foo | --bar]
1857 PROG: error: argument --bar: not allowed with argument --foo
1858
Georg Brandle0bf91d2010-10-17 10:34:28 +00001859 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001860 argument, to indicate that at least one of the mutually exclusive arguments
1861 is required::
1862
1863 >>> parser = argparse.ArgumentParser(prog='PROG')
1864 >>> group = parser.add_mutually_exclusive_group(required=True)
1865 >>> group.add_argument('--foo', action='store_true')
1866 >>> group.add_argument('--bar', action='store_false')
1867 >>> parser.parse_args([])
1868 usage: PROG [-h] (--foo | --bar)
1869 PROG: error: one of the arguments --foo --bar is required
1870
1871 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001872 *title* and *description* arguments of
1873 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001874
1875
1876Parser defaults
1877^^^^^^^^^^^^^^^
1878
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001879.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001880
1881 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001882 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001883 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001884 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001885 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001886
1887 >>> parser = argparse.ArgumentParser()
1888 >>> parser.add_argument('foo', type=int)
1889 >>> parser.set_defaults(bar=42, baz='badger')
1890 >>> parser.parse_args(['736'])
1891 Namespace(bar=42, baz='badger', foo=736)
1892
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001893 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001894
1895 >>> parser = argparse.ArgumentParser()
1896 >>> parser.add_argument('--foo', default='bar')
1897 >>> parser.set_defaults(foo='spam')
1898 >>> parser.parse_args([])
1899 Namespace(foo='spam')
1900
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001901 Parser-level defaults can be particularly useful when working with multiple
1902 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1903 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001904
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001905.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001906
1907 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001908 :meth:`~ArgumentParser.add_argument` or by
1909 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001910
1911 >>> parser = argparse.ArgumentParser()
1912 >>> parser.add_argument('--foo', default='badger')
1913 >>> parser.get_default('foo')
1914 'badger'
1915
1916
1917Printing help
1918^^^^^^^^^^^^^
1919
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001920In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1921care of formatting and printing any usage or error messages. However, several
1922formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001923
Georg Brandle0bf91d2010-10-17 10:34:28 +00001924.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001925
1926 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001927 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001928 assumed.
1929
Georg Brandle0bf91d2010-10-17 10:34:28 +00001930.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001931
1932 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001933 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001934 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001935
1936There are also variants of these methods that simply return a string instead of
1937printing it:
1938
Georg Brandle0bf91d2010-10-17 10:34:28 +00001939.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001940
1941 Return a string containing a brief description of how the
1942 :class:`ArgumentParser` should be invoked on the command line.
1943
Georg Brandle0bf91d2010-10-17 10:34:28 +00001944.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001945
1946 Return a string containing a help message, including the program usage and
1947 information about the arguments registered with the :class:`ArgumentParser`.
1948
1949
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001950Partial parsing
1951^^^^^^^^^^^^^^^
1952
Georg Brandle0bf91d2010-10-17 10:34:28 +00001953.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001954
Georg Brandl69518bc2011-04-16 16:44:54 +02001955Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001956the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001957:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001958:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1959extra arguments are present. Instead, it returns a two item tuple containing
1960the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001961
1962::
1963
1964 >>> parser = argparse.ArgumentParser()
1965 >>> parser.add_argument('--foo', action='store_true')
1966 >>> parser.add_argument('bar')
1967 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1968 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1969
Eli Benderskyf3114532013-12-02 05:49:54 -08001970.. warning::
1971 :ref:`Prefix matching <prefix-matching>` rules apply to
1972 :meth:`parse_known_args`. The parser may consume an option even if it's just
1973 a prefix of one of its known options, instead of leaving it in the remaining
1974 arguments list.
1975
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001976
1977Customizing file parsing
1978^^^^^^^^^^^^^^^^^^^^^^^^
1979
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001980.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001981
Georg Brandle0bf91d2010-10-17 10:34:28 +00001982 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001983 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft8b852f12014-05-20 12:58:38 -04001984 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001985 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001986
Georg Brandle0bf91d2010-10-17 10:34:28 +00001987 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001988 the argument file. It returns a list of arguments parsed from this string.
1989 The method is called once per line read from the argument file, in order.
1990
1991 A useful override of this method is one that treats each space-separated word
Berker Peksag5493e472016-10-17 06:14:17 +03001992 as an argument. The following example demonstrates how to do this::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001993
Berker Peksag5493e472016-10-17 06:14:17 +03001994 class MyArgumentParser(argparse.ArgumentParser):
1995 def convert_arg_line_to_args(self, arg_line):
1996 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001997
1998
Georg Brandl93754922010-10-17 10:28:04 +00001999Exiting methods
2000^^^^^^^^^^^^^^^
2001
2002.. method:: ArgumentParser.exit(status=0, message=None)
2003
2004 This method terminates the program, exiting with the specified *status*
2005 and, if given, it prints a *message* before that.
2006
2007.. method:: ArgumentParser.error(message)
2008
2009 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08002010 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00002011
R. David Murray0f6b9d22017-09-06 20:25:40 -04002012
2013Intermixed parsing
2014^^^^^^^^^^^^^^^^^^
2015
2016.. method:: ArgumentParser.parse_intermixed_args(args=None, namespace=None)
2017.. method:: ArgumentParser.parse_known_intermixed_args(args=None, namespace=None)
2018
2019A number of Unix commands allow the user to intermix optional arguments with
2020positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args`
2021and :meth:`~ArgumentParser.parse_known_intermixed_args` methods
2022support this parsing style.
2023
2024These parsers do not support all the argparse features, and will raise
2025exceptions if unsupported features are used. In particular, subparsers,
2026``argparse.REMAINDER``, and mutually exclusive groups that include both
2027optionals and positionals are not supported.
2028
2029The following example shows the difference between
2030:meth:`~ArgumentParser.parse_known_args` and
2031:meth:`~ArgumentParser.parse_intermixed_args`: the former returns ``['2',
2032'3']`` as unparsed arguments, while the latter collects all the positionals
2033into ``rest``. ::
2034
2035 >>> parser = argparse.ArgumentParser()
2036 >>> parser.add_argument('--foo')
2037 >>> parser.add_argument('cmd')
2038 >>> parser.add_argument('rest', nargs='*', type=int)
2039 >>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
2040 (Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
2041 >>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
2042 Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])
2043
2044:meth:`~ArgumentParser.parse_known_intermixed_args` returns a two item tuple
2045containing the populated namespace and the list of remaining argument strings.
2046:meth:`~ArgumentParser.parse_intermixed_args` raises an error if there are any
2047remaining unparsed argument strings.
2048
2049.. versionadded:: 3.7
2050
Raymond Hettinger677e10a2010-12-07 06:45:30 +00002051.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00002052
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002053Upgrading optparse code
2054-----------------------
2055
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002056Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002057with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
2058transparently, particularly with the changes required to support the new
2059``nargs=`` specifiers and better usage messages. When most everything in
2060:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
2061longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002062
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03002063The :mod:`argparse` module improves on the standard library :mod:`optparse`
2064module in a number of ways including:
2065
2066* Handling positional arguments.
2067* Supporting sub-commands.
2068* Allowing alternative option prefixes like ``+`` and ``/``.
2069* Handling zero-or-more and one-or-more style arguments.
2070* Producing more informative usage messages.
2071* Providing a much simpler interface for custom ``type`` and ``action``.
2072
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002073A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002074
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002075* Replace all :meth:`optparse.OptionParser.add_option` calls with
2076 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002077
R David Murray5e0c5712012-03-30 18:07:42 -04002078* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00002079 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04002080 calls for the positional arguments. Keep in mind that what was previously
R. David Murray0c7983e2017-09-04 16:17:26 -04002081 called ``options``, now in the :mod:`argparse` context is called ``args``.
2082
2083* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
R. David Murray0f6b9d22017-09-06 20:25:40 -04002084 by using :meth:`~ArgumentParser.parse_intermixed_args` instead of
2085 :meth:`~ArgumentParser.parse_args`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002086
2087* Replace callback actions and the ``callback_*`` keyword arguments with
2088 ``type`` or ``action`` arguments.
2089
2090* Replace string names for ``type`` keyword arguments with the corresponding
2091 type objects (e.g. int, float, complex, etc).
2092
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002093* Replace :class:`optparse.Values` with :class:`Namespace` and
2094 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
2095 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002096
2097* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03002098 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002099 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00002100
2101* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panterd21e0b52015-10-10 10:36:22 +00002102 ``parser.add_argument('--version', action='version', version='<the version>')``.