blob: 1973afc49452632107e76202eb41c60ea8d55506 [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
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000185The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000186
187
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300188prog
189^^^^
190
Martin Panter0f0eac42016-09-07 11:04:41 +0000191By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300192how to display the name of the program in help messages. This default is almost
193always desirable because it will make the help messages match how the program was
194invoked on the command line. For example, consider a file named
195``myprogram.py`` with the following code::
196
197 import argparse
198 parser = argparse.ArgumentParser()
199 parser.add_argument('--foo', help='foo help')
200 args = parser.parse_args()
201
202The help for this program will display ``myprogram.py`` as the program name
Martin Panter1050d2d2016-07-26 11:18:21 +0200203(regardless of where the program was invoked from):
204
205.. code-block:: shell-session
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300206
207 $ python myprogram.py --help
208 usage: myprogram.py [-h] [--foo FOO]
209
210 optional arguments:
211 -h, --help show this help message and exit
212 --foo FOO foo help
213 $ cd ..
Martin Panter536d70e2017-01-14 08:23:08 +0000214 $ python subdir/myprogram.py --help
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300215 usage: myprogram.py [-h] [--foo FOO]
216
217 optional arguments:
218 -h, --help show this help message and exit
219 --foo FOO foo help
220
221To change this default behavior, another value can be supplied using the
222``prog=`` argument to :class:`ArgumentParser`::
223
224 >>> parser = argparse.ArgumentParser(prog='myprogram')
225 >>> parser.print_help()
226 usage: myprogram [-h]
227
228 optional arguments:
229 -h, --help show this help message and exit
230
231Note that the program name, whether determined from ``sys.argv[0]`` or from the
232``prog=`` argument, is available to help messages using the ``%(prog)s`` format
233specifier.
234
235::
236
237 >>> parser = argparse.ArgumentParser(prog='myprogram')
238 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
239 >>> parser.print_help()
240 usage: myprogram [-h] [--foo FOO]
241
242 optional arguments:
243 -h, --help show this help message and exit
244 --foo FOO foo of the myprogram program
245
246
247usage
248^^^^^
249
250By default, :class:`ArgumentParser` calculates the usage message from the
251arguments it contains::
252
253 >>> parser = argparse.ArgumentParser(prog='PROG')
254 >>> parser.add_argument('--foo', nargs='?', help='foo help')
255 >>> parser.add_argument('bar', nargs='+', help='bar help')
256 >>> parser.print_help()
257 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
258
259 positional arguments:
260 bar bar help
261
262 optional arguments:
263 -h, --help show this help message and exit
264 --foo [FOO] foo help
265
266The default message can be overridden with the ``usage=`` keyword argument::
267
268 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
269 >>> parser.add_argument('--foo', nargs='?', help='foo help')
270 >>> parser.add_argument('bar', nargs='+', help='bar help')
271 >>> parser.print_help()
272 usage: PROG [options]
273
274 positional arguments:
275 bar bar help
276
277 optional arguments:
278 -h, --help show this help message and exit
279 --foo [FOO] foo help
280
281The ``%(prog)s`` format specifier is available to fill in the program name in
282your usage messages.
283
284
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000285description
286^^^^^^^^^^^
287
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000288Most calls to the :class:`ArgumentParser` constructor will use the
289``description=`` keyword argument. This argument gives a brief description of
290what the program does and how it works. In help messages, the description is
291displayed between the command-line usage string and the help messages for the
292various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000293
294 >>> parser = argparse.ArgumentParser(description='A foo that bars')
295 >>> parser.print_help()
296 usage: argparse.py [-h]
297
298 A foo that bars
299
300 optional arguments:
301 -h, --help show this help message and exit
302
303By default, the description will be line-wrapped so that it fits within the
304given space. To change this behavior, see the formatter_class_ argument.
305
306
307epilog
308^^^^^^
309
310Some programs like to display additional description of the program after the
311description of the arguments. Such text can be specified using the ``epilog=``
312argument to :class:`ArgumentParser`::
313
314 >>> parser = argparse.ArgumentParser(
315 ... description='A foo that bars',
316 ... epilog="And that's how you'd foo a bar")
317 >>> parser.print_help()
318 usage: argparse.py [-h]
319
320 A foo that bars
321
322 optional arguments:
323 -h, --help show this help message and exit
324
325 And that's how you'd foo a bar
326
327As with the description_ argument, the ``epilog=`` text is by default
328line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000329argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000330
331
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000332parents
333^^^^^^^
334
335Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000336repeating the definitions of these arguments, a single parser with all the
337shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
338can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
339objects, collects all the positional and optional actions from them, and adds
340these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000341
342 >>> parent_parser = argparse.ArgumentParser(add_help=False)
343 >>> parent_parser.add_argument('--parent', type=int)
344
345 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
346 >>> foo_parser.add_argument('foo')
347 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
348 Namespace(foo='XXX', parent=2)
349
350 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
351 >>> bar_parser.add_argument('--bar')
352 >>> bar_parser.parse_args(['--bar', 'YYY'])
353 Namespace(bar='YYY', parent=None)
354
355Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000356:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
357and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000358
Steven Bethardd186f992011-03-26 21:49:00 +0100359.. note::
360 You must fully initialize the parsers before passing them via ``parents=``.
361 If you change the parent parsers after the child parser, those changes will
362 not be reflected in the child.
363
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000364
365formatter_class
366^^^^^^^^^^^^^^^
367
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000368:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300369specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300370classes:
371
372.. class:: RawDescriptionHelpFormatter
373 RawTextHelpFormatter
374 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300375 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000376
Steven Bethard0331e902011-03-26 14:48:04 +0100377:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
378more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000379By default, :class:`ArgumentParser` objects line-wrap the description_ and
380epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000381
382 >>> parser = argparse.ArgumentParser(
383 ... prog='PROG',
384 ... description='''this description
385 ... was indented weird
386 ... but that is okay''',
387 ... epilog='''
388 ... likewise for this epilog whose whitespace will
389 ... be cleaned up and whose words will be wrapped
390 ... across a couple lines''')
391 >>> parser.print_help()
392 usage: PROG [-h]
393
394 this description was indented weird but that is okay
395
396 optional arguments:
397 -h, --help show this help message and exit
398
399 likewise for this epilog whose whitespace will be cleaned up and whose words
400 will be wrapped across a couple lines
401
Steven Bethard0331e902011-03-26 14:48:04 +0100402Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000403indicates that description_ and epilog_ are already correctly formatted and
404should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000405
406 >>> parser = argparse.ArgumentParser(
407 ... prog='PROG',
408 ... formatter_class=argparse.RawDescriptionHelpFormatter,
409 ... description=textwrap.dedent('''\
410 ... Please do not mess up this text!
411 ... --------------------------------
412 ... I have indented it
413 ... exactly the way
414 ... I want it
415 ... '''))
416 >>> parser.print_help()
417 usage: PROG [-h]
418
419 Please do not mess up this text!
420 --------------------------------
421 I have indented it
422 exactly the way
423 I want it
424
425 optional arguments:
426 -h, --help show this help message and exit
427
Steven Bethard0331e902011-03-26 14:48:04 +0100428:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Elena Oat397c4672017-09-07 23:06:45 +0300429including argument descriptions. However, multiple new lines are replaced with
430one. If you wish to preserve multiple blank lines, add spaces between the
431newlines.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000432
Steven Bethard0331e902011-03-26 14:48:04 +0100433:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
434default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000435
436 >>> parser = argparse.ArgumentParser(
437 ... prog='PROG',
438 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
439 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
440 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
441 >>> parser.print_help()
442 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
443
444 positional arguments:
445 bar BAR! (default: [1, 2, 3])
446
447 optional arguments:
448 -h, --help show this help message and exit
449 --foo FOO FOO! (default: 42)
450
Steven Bethard0331e902011-03-26 14:48:04 +0100451:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300452argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100453as the regular formatter does)::
454
455 >>> parser = argparse.ArgumentParser(
456 ... prog='PROG',
457 ... formatter_class=argparse.MetavarTypeHelpFormatter)
458 >>> parser.add_argument('--foo', type=int)
459 >>> parser.add_argument('bar', type=float)
460 >>> parser.print_help()
461 usage: PROG [-h] [--foo int] float
462
463 positional arguments:
464 float
465
466 optional arguments:
467 -h, --help show this help message and exit
468 --foo int
469
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000470
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300471prefix_chars
472^^^^^^^^^^^^
473
474Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
475Parsers that need to support different or additional prefix
476characters, e.g. for options
477like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
478to the ArgumentParser constructor::
479
480 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
481 >>> parser.add_argument('+f')
482 >>> parser.add_argument('++bar')
483 >>> parser.parse_args('+f X ++bar Y'.split())
484 Namespace(bar='Y', f='X')
485
486The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
487characters that does not include ``-`` will cause ``-f/--foo`` options to be
488disallowed.
489
490
491fromfile_prefix_chars
492^^^^^^^^^^^^^^^^^^^^^
493
494Sometimes, for example when dealing with a particularly long argument lists, it
495may make sense to keep the list of arguments in a file rather than typing it out
496at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
497:class:`ArgumentParser` constructor, then arguments that start with any of the
498specified characters will be treated as files, and will be replaced by the
499arguments they contain. For example::
500
501 >>> with open('args.txt', 'w') as fp:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300502 ... fp.write('-f\nbar')
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300503 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
504 >>> parser.add_argument('-f')
505 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
506 Namespace(f='bar')
507
508Arguments read from a file must by default be one per line (but see also
509:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
510were in the same place as the original file referencing argument on the command
511line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
512is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
513
514The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
515arguments will never be treated as file references.
516
517
518argument_default
519^^^^^^^^^^^^^^^^
520
521Generally, argument defaults are specified either by passing a default to
522:meth:`~ArgumentParser.add_argument` or by calling the
523:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
524pairs. Sometimes however, it may be useful to specify a single parser-wide
525default for arguments. This can be accomplished by passing the
526``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
527to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
528calls, we supply ``argument_default=SUPPRESS``::
529
530 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
531 >>> parser.add_argument('--foo')
532 >>> parser.add_argument('bar', nargs='?')
533 >>> parser.parse_args(['--foo', '1', 'BAR'])
534 Namespace(bar='BAR', foo='1')
535 >>> parser.parse_args([])
536 Namespace()
537
Berker Peksag8089cd62015-02-14 01:39:17 +0200538.. _allow_abbrev:
539
540allow_abbrev
541^^^^^^^^^^^^
542
543Normally, when you pass an argument list to the
Martin Panterd2ad5712015-11-02 04:20:33 +0000544:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`,
Berker Peksag8089cd62015-02-14 01:39:17 +0200545it :ref:`recognizes abbreviations <prefix-matching>` of long options.
546
547This feature can be disabled by setting ``allow_abbrev`` to ``False``::
548
549 >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
550 >>> parser.add_argument('--foobar', action='store_true')
551 >>> parser.add_argument('--foonley', action='store_false')
Berker Peksage7e497b2015-03-12 20:47:41 +0200552 >>> parser.parse_args(['--foon'])
Berker Peksag8089cd62015-02-14 01:39:17 +0200553 usage: PROG [-h] [--foobar] [--foonley]
554 PROG: error: unrecognized arguments: --foon
555
556.. versionadded:: 3.5
557
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300558
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000559conflict_handler
560^^^^^^^^^^^^^^^^
561
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000562:class:`ArgumentParser` objects do not allow two actions with the same option
Martin Panter0f0eac42016-09-07 11:04:41 +0000563string. By default, :class:`ArgumentParser` objects raise an exception if an
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000564attempt is made to create an argument with an option string that is already in
565use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000566
567 >>> parser = argparse.ArgumentParser(prog='PROG')
568 >>> parser.add_argument('-f', '--foo', help='old foo help')
569 >>> parser.add_argument('--foo', help='new foo help')
570 Traceback (most recent call last):
571 ..
572 ArgumentError: argument --foo: conflicting option string(s): --foo
573
574Sometimes (e.g. when using parents_) it may be useful to simply override any
575older arguments with the same option string. To get this behavior, the value
576``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000577:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000578
579 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
580 >>> parser.add_argument('-f', '--foo', help='old foo help')
581 >>> parser.add_argument('--foo', help='new foo help')
582 >>> parser.print_help()
583 usage: PROG [-h] [-f FOO] [--foo FOO]
584
585 optional arguments:
586 -h, --help show this help message and exit
587 -f FOO old foo help
588 --foo FOO new foo help
589
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000590Note that :class:`ArgumentParser` objects only remove an action if all of its
591option strings are overridden. So, in the example above, the old ``-f/--foo``
592action is retained as the ``-f`` action, because only the ``--foo`` option
593string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000594
595
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300596add_help
597^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000598
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300599By default, ArgumentParser objects add an option which simply displays
600the parser's help message. For example, consider a file named
601``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000602
603 import argparse
604 parser = argparse.ArgumentParser()
605 parser.add_argument('--foo', help='foo help')
606 args = parser.parse_args()
607
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300608If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Martin Panter1050d2d2016-07-26 11:18:21 +0200609help will be printed:
610
611.. code-block:: shell-session
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000612
613 $ python myprogram.py --help
614 usage: myprogram.py [-h] [--foo FOO]
615
616 optional arguments:
617 -h, --help show this help message and exit
618 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000619
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300620Occasionally, it may be useful to disable the addition of this help option.
621This can be achieved by passing ``False`` as the ``add_help=`` argument to
622:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000623
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300624 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
625 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000626 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300627 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000628
629 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300630 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000631
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300632The help option is typically ``-h/--help``. The exception to this is
633if the ``prefix_chars=`` is specified and does not include ``-``, in
634which case ``-h`` and ``--help`` are not valid options. In
635this case, the first character in ``prefix_chars`` is used to prefix
636the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000637
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300638 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000639 >>> parser.print_help()
Georg Brandld2914ce2013-10-06 09:50:36 +0200640 usage: PROG [+h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000641
642 optional arguments:
Georg Brandld2914ce2013-10-06 09:50:36 +0200643 +h, ++help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000644
645
646The add_argument() method
647-------------------------
648
Georg Brandlc9007082011-01-09 09:04:08 +0000649.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
650 [const], [default], [type], [choices], [required], \
651 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000652
Georg Brandl69518bc2011-04-16 16:44:54 +0200653 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000654 has its own more detailed description below, but in short they are:
655
656 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300657 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000658
659 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200660 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000661
662 * nargs_ - The number of command-line arguments that should be consumed.
663
664 * const_ - A constant value required by some action_ and nargs_ selections.
665
666 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200667 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000668
Ezio Melotti2409d772011-04-16 23:13:50 +0300669 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000670
671 * choices_ - A container of the allowable values for the argument.
672
673 * required_ - Whether or not the command-line option may be omitted
674 (optionals only).
675
676 * help_ - A brief description of what the argument does.
677
678 * metavar_ - A name for the argument in usage messages.
679
680 * dest_ - The name of the attribute to be added to the object returned by
681 :meth:`parse_args`.
682
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000683The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000684
Georg Brandle0bf91d2010-10-17 10:34:28 +0000685
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000686name or flags
687^^^^^^^^^^^^^
688
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300689The :meth:`~ArgumentParser.add_argument` method must know whether an optional
690argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
691filenames, is expected. The first arguments passed to
692:meth:`~ArgumentParser.add_argument` must therefore be either a series of
693flags, or a simple argument name. For example, an optional argument could
694be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000695
696 >>> parser.add_argument('-f', '--foo')
697
698while a positional argument could be created like::
699
700 >>> parser.add_argument('bar')
701
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300702When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
703identified by the ``-`` prefix, and the remaining arguments will be assumed to
704be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000705
706 >>> parser = argparse.ArgumentParser(prog='PROG')
707 >>> parser.add_argument('-f', '--foo')
708 >>> parser.add_argument('bar')
709 >>> parser.parse_args(['BAR'])
710 Namespace(bar='BAR', foo=None)
711 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
712 Namespace(bar='BAR', foo='FOO')
713 >>> parser.parse_args(['--foo', 'FOO'])
714 usage: PROG [-h] [-f FOO] bar
suic8604e82932018-04-11 20:45:04 +0200715 PROG: error: the following arguments are required: bar
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000716
Georg Brandle0bf91d2010-10-17 10:34:28 +0000717
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000718action
719^^^^^^
720
Éric Araujod9d7bca2011-08-10 04:19:03 +0200721:class:`ArgumentParser` objects associate command-line arguments with actions. These
722actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000723them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300724:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -0500725how the command-line arguments should be handled. The supplied actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000726
727* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300728 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000729
730 >>> parser = argparse.ArgumentParser()
731 >>> parser.add_argument('--foo')
732 >>> parser.parse_args('--foo 1'.split())
733 Namespace(foo='1')
734
735* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panterb4912b82016-04-09 03:49:48 +0000736 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300737 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000738
739 >>> parser = argparse.ArgumentParser()
740 >>> parser.add_argument('--foo', action='store_const', const=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000741 >>> parser.parse_args(['--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000742 Namespace(foo=42)
743
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800744* ``'store_true'`` and ``'store_false'`` - These are special cases of
745 ``'store_const'`` used for storing the values ``True`` and ``False``
746 respectively. In addition, they create default values of ``False`` and
747 ``True`` respectively. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000748
749 >>> parser = argparse.ArgumentParser()
750 >>> parser.add_argument('--foo', action='store_true')
751 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800752 >>> parser.add_argument('--baz', action='store_false')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000753 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800754 Namespace(foo=True, bar=False, baz=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000755
756* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000757 list. This is useful to allow an option to be specified multiple times.
758 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000759
760 >>> parser = argparse.ArgumentParser()
761 >>> parser.add_argument('--foo', action='append')
762 >>> parser.parse_args('--foo 1 --foo 2'.split())
763 Namespace(foo=['1', '2'])
764
765* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000766 the const_ keyword argument to the list. (Note that the const_ keyword
767 argument defaults to ``None``.) The ``'append_const'`` action is typically
768 useful when multiple arguments need to store constants to the same list. For
769 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000770
771 >>> parser = argparse.ArgumentParser()
772 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
773 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
774 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200775 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000776
Sandro Tosi98492a52012-01-04 23:25:04 +0100777* ``'count'`` - This counts the number of times a keyword argument occurs. For
778 example, this is useful for increasing verbosity levels::
779
780 >>> parser = argparse.ArgumentParser()
781 >>> parser.add_argument('--verbose', '-v', action='count')
Martin Panterf5e60482016-04-26 11:41:25 +0000782 >>> parser.parse_args(['-vvv'])
Sandro Tosi98492a52012-01-04 23:25:04 +0100783 Namespace(verbose=3)
784
785* ``'help'`` - This prints a complete help message for all the options in the
786 current parser and then exits. By default a help action is automatically
787 added to the parser. See :class:`ArgumentParser` for details of how the
788 output is created.
789
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000790* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300791 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100792 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000793
794 >>> import argparse
795 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000796 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
797 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000798 PROG 2.0
799
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400800You may also specify an arbitrary action by passing an Action subclass or
801other object that implements the same interface. The recommended way to do
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400802this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400803and optionally the ``__init__`` method.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000804
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000805An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000806
807 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400808 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
809 ... if nargs is not None:
810 ... raise ValueError("nargs not allowed")
811 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000812 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000813 ... print('%r %r %r' % (namespace, values, option_string))
814 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000815 ...
816 >>> parser = argparse.ArgumentParser()
817 >>> parser.add_argument('--foo', action=FooAction)
818 >>> parser.add_argument('bar', action=FooAction)
819 >>> args = parser.parse_args('1 --foo 2'.split())
820 Namespace(bar=None, foo=None) '1' None
821 Namespace(bar='1', foo=None) '2' '--foo'
822 >>> args
823 Namespace(bar='1', foo='2')
824
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400825For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000826
827nargs
828^^^^^
829
830ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000831single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300832different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000833values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000834
Éric Araujoc3ef0372012-02-20 01:44:55 +0100835* ``N`` (an integer). ``N`` arguments from the command line will be gathered
836 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000837
Georg Brandl682d7e02010-10-06 10:26:05 +0000838 >>> parser = argparse.ArgumentParser()
839 >>> parser.add_argument('--foo', nargs=2)
840 >>> parser.add_argument('bar', nargs=1)
841 >>> parser.parse_args('c --foo a b'.split())
842 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000843
Georg Brandl682d7e02010-10-06 10:26:05 +0000844 Note that ``nargs=1`` produces a list of one item. This is different from
845 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000846
Éric Araujofde92422011-08-19 01:30:26 +0200847* ``'?'``. One argument will be consumed from the command line if possible, and
848 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000849 default_ will be produced. Note that for optional arguments, there is an
850 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200851 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000852 examples to illustrate this::
853
854 >>> parser = argparse.ArgumentParser()
855 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
856 >>> parser.add_argument('bar', nargs='?', default='d')
Martin Panterf5e60482016-04-26 11:41:25 +0000857 >>> parser.parse_args(['XX', '--foo', 'YY'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000858 Namespace(bar='XX', foo='YY')
Martin Panterf5e60482016-04-26 11:41:25 +0000859 >>> parser.parse_args(['XX', '--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000860 Namespace(bar='XX', foo='c')
Martin Panterf5e60482016-04-26 11:41:25 +0000861 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000862 Namespace(bar='d', foo='d')
863
864 One of the more common uses of ``nargs='?'`` is to allow optional input and
865 output files::
866
867 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000868 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
869 ... default=sys.stdin)
870 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
871 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000872 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000873 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
874 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000875 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000876 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
877 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000878
Éric Araujod9d7bca2011-08-10 04:19:03 +0200879* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000880 it generally doesn't make much sense to have more than one positional argument
881 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
882 possible. For example::
883
884 >>> parser = argparse.ArgumentParser()
885 >>> parser.add_argument('--foo', nargs='*')
886 >>> parser.add_argument('--bar', nargs='*')
887 >>> parser.add_argument('baz', nargs='*')
888 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
889 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
890
891* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
892 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200893 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000894
895 >>> parser = argparse.ArgumentParser(prog='PROG')
896 >>> parser.add_argument('foo', nargs='+')
Martin Panterf5e60482016-04-26 11:41:25 +0000897 >>> parser.parse_args(['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000898 Namespace(foo=['a', 'b'])
Martin Panterf5e60482016-04-26 11:41:25 +0000899 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000900 usage: PROG [-h] foo [foo ...]
suic8604e82932018-04-11 20:45:04 +0200901 PROG: error: the following arguments are required: foo
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000902
R. David Murray0c7983e2017-09-04 16:17:26 -0400903.. _`argparse.REMAINDER`:
904
Sandro Tosida8e11a2012-01-19 22:23:00 +0100905* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
906 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100907 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100908
909 >>> parser = argparse.ArgumentParser(prog='PROG')
910 >>> parser.add_argument('--foo')
911 >>> parser.add_argument('command')
912 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100913 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100914 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100915
Éric Araujod9d7bca2011-08-10 04:19:03 +0200916If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200917is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000918will be consumed and a single item (not a list) will be produced.
919
920
921const
922^^^^^
923
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300924The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
925constant values that are not read from the command line but are required for
926the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000927
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300928* When :meth:`~ArgumentParser.add_argument` is called with
929 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100930 ``const`` value to one of the attributes of the object returned by
931 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000932
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300933* When :meth:`~ArgumentParser.add_argument` is called with option strings
934 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200935 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300936 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200937 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300938 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000939
Martin Panterb4912b82016-04-09 03:49:48 +0000940With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panter119e5022016-04-16 09:28:57 +0000941keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000942
943
944default
945^^^^^^^
946
947All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300948command line. The ``default`` keyword argument of
949:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200950specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300951For optional arguments, the ``default`` value is used when the option string
952was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000953
954 >>> parser = argparse.ArgumentParser()
955 >>> parser.add_argument('--foo', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000956 >>> parser.parse_args(['--foo', '2'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000957 Namespace(foo='2')
Martin Panterf5e60482016-04-26 11:41:25 +0000958 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000959 Namespace(foo=42)
960
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400961If the ``default`` value is a string, the parser parses the value as if it
962were a command-line argument. In particular, the parser applies any type_
963conversion argument, if provided, before setting the attribute on the
964:class:`Namespace` return value. Otherwise, the parser uses the value as is::
965
966 >>> parser = argparse.ArgumentParser()
967 >>> parser.add_argument('--length', default='10', type=int)
968 >>> parser.add_argument('--width', default=10.5, type=int)
969 >>> parser.parse_args()
970 Namespace(length=10, width=10.5)
971
Éric Araujo543edbd2011-08-19 01:45:12 +0200972For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200973is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000974
975 >>> parser = argparse.ArgumentParser()
976 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000977 >>> parser.parse_args(['a'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000978 Namespace(foo='a')
Martin Panterf5e60482016-04-26 11:41:25 +0000979 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000980 Namespace(foo=42)
981
982
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000983Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
Julien Palard78553132018-03-28 23:14:15 +0200984command-line argument was not present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000985
986 >>> parser = argparse.ArgumentParser()
987 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
988 >>> parser.parse_args([])
989 Namespace()
990 >>> parser.parse_args(['--foo', '1'])
991 Namespace(foo='1')
992
993
994type
995^^^^
996
Éric Araujod9d7bca2011-08-10 04:19:03 +0200997By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300998strings. However, quite often the command-line string should instead be
999interpreted as another type, like a :class:`float` or :class:`int`. The
1000``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +02001001necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001002types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001003
1004 >>> parser = argparse.ArgumentParser()
1005 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +00001006 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001007 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +00001008 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001009
Barry Warsaw1dedd0a2012-09-25 10:37:58 -04001010See the section on the default_ keyword argument for information on when the
1011``type`` argument is applied to default arguments.
1012
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001013To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001014factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
1015``errors=`` arguments of the :func:`open` function. For example,
1016``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001017
1018 >>> parser = argparse.ArgumentParser()
1019 >>> parser.add_argument('bar', type=argparse.FileType('w'))
1020 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +00001021 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001022
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001023``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +02001024the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001025
1026 >>> def perfect_square(string):
1027 ... value = int(string)
1028 ... sqrt = math.sqrt(value)
1029 ... if sqrt != int(sqrt):
1030 ... msg = "%r is not a perfect square" % string
1031 ... raise argparse.ArgumentTypeError(msg)
1032 ... return value
1033 ...
1034 >>> parser = argparse.ArgumentParser(prog='PROG')
1035 >>> parser.add_argument('foo', type=perfect_square)
Martin Panterf5e60482016-04-26 11:41:25 +00001036 >>> parser.parse_args(['9'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001037 Namespace(foo=9)
Martin Panterf5e60482016-04-26 11:41:25 +00001038 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001039 usage: PROG [-h] foo
1040 PROG: error: argument foo: '7' is not a perfect square
1041
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001042The choices_ keyword argument may be more convenient for type checkers that
1043simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001044
1045 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001046 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Martin Panterf5e60482016-04-26 11:41:25 +00001047 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001048 Namespace(foo=7)
Martin Panterf5e60482016-04-26 11:41:25 +00001049 >>> parser.parse_args(['11'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001050 usage: PROG [-h] {5,6,7,8,9}
1051 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1052
1053See the choices_ section for more details.
1054
1055
1056choices
1057^^^^^^^
1058
Éric Araujod9d7bca2011-08-10 04:19:03 +02001059Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001060These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001061argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001062parsed, argument values will be checked, and an error message will be displayed
1063if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001064
Chris Jerdonek174ef672013-01-11 19:26:44 -08001065 >>> parser = argparse.ArgumentParser(prog='game.py')
1066 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1067 >>> parser.parse_args(['rock'])
1068 Namespace(move='rock')
1069 >>> parser.parse_args(['fire'])
1070 usage: game.py [-h] {rock,paper,scissors}
1071 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1072 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001073
Chris Jerdonek174ef672013-01-11 19:26:44 -08001074Note that inclusion in the *choices* container is checked after any type_
1075conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001076container should match the type_ specified::
1077
Chris Jerdonek174ef672013-01-11 19:26:44 -08001078 >>> parser = argparse.ArgumentParser(prog='doors.py')
1079 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1080 >>> print(parser.parse_args(['3']))
1081 Namespace(door=3)
1082 >>> parser.parse_args(['4'])
1083 usage: doors.py [-h] {1,2,3}
1084 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001085
Chris Jerdonek174ef672013-01-11 19:26:44 -08001086Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001087value, so :class:`dict` objects, :class:`set` objects, custom containers,
1088etc. are all supported.
1089
1090
1091required
1092^^^^^^^^
1093
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001094In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001095indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001096To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001097keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001098
1099 >>> parser = argparse.ArgumentParser()
1100 >>> parser.add_argument('--foo', required=True)
1101 >>> parser.parse_args(['--foo', 'BAR'])
1102 Namespace(foo='BAR')
1103 >>> parser.parse_args([])
1104 usage: argparse.py [-h] [--foo FOO]
1105 argparse.py: error: option --foo is required
1106
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001107As the example shows, if an option is marked as ``required``,
1108:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1109present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001110
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001111.. note::
1112
1113 Required options are generally considered bad form because users expect
1114 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001115
1116
1117help
1118^^^^
1119
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001120The ``help`` value is a string containing a brief description of the argument.
1121When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001122command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001123argument::
1124
1125 >>> parser = argparse.ArgumentParser(prog='frobble')
1126 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001127 ... help='foo the bars before frobbling')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001128 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001129 ... help='one of the bars to be frobbled')
Martin Panterf5e60482016-04-26 11:41:25 +00001130 >>> parser.parse_args(['-h'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001131 usage: frobble [-h] [--foo] bar [bar ...]
1132
1133 positional arguments:
1134 bar one of the bars to be frobbled
1135
1136 optional arguments:
1137 -h, --help show this help message and exit
1138 --foo foo the bars before frobbling
1139
1140The ``help`` strings can include various format specifiers to avoid repetition
1141of things like the program name or the argument default_. The available
1142specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001143:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001144
1145 >>> parser = argparse.ArgumentParser(prog='frobble')
1146 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001147 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001148 >>> parser.print_help()
1149 usage: frobble [-h] [bar]
1150
1151 positional arguments:
1152 bar the bar to frobble (default: 42)
1153
1154 optional arguments:
1155 -h, --help show this help message and exit
1156
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001157As the help string supports %-formatting, if you want a literal ``%`` to appear
1158in the help string, you must escape it as ``%%``.
1159
Sandro Tosiea320ab2012-01-03 18:37:03 +01001160:mod:`argparse` supports silencing the help entry for certain options, by
1161setting the ``help`` value to ``argparse.SUPPRESS``::
1162
1163 >>> parser = argparse.ArgumentParser(prog='frobble')
1164 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1165 >>> parser.print_help()
1166 usage: frobble [-h]
1167
1168 optional arguments:
1169 -h, --help show this help message and exit
1170
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001171
1172metavar
1173^^^^^^^
1174
Sandro Tosi32587fb2013-01-11 10:49:00 +01001175When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001176to each expected argument. By default, ArgumentParser objects use the dest_
1177value as the "name" of each object. By default, for positional argument
1178actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001179the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001180``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001181optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001182will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001183
1184 >>> parser = argparse.ArgumentParser()
1185 >>> parser.add_argument('--foo')
1186 >>> parser.add_argument('bar')
1187 >>> parser.parse_args('X --foo Y'.split())
1188 Namespace(bar='X', foo='Y')
1189 >>> parser.print_help()
1190 usage: [-h] [--foo FOO] bar
1191
1192 positional arguments:
1193 bar
1194
1195 optional arguments:
1196 -h, --help show this help message and exit
1197 --foo FOO
1198
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001199An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001200
1201 >>> parser = argparse.ArgumentParser()
1202 >>> parser.add_argument('--foo', metavar='YYY')
1203 >>> parser.add_argument('bar', metavar='XXX')
1204 >>> parser.parse_args('X --foo Y'.split())
1205 Namespace(bar='X', foo='Y')
1206 >>> parser.print_help()
1207 usage: [-h] [--foo YYY] XXX
1208
1209 positional arguments:
1210 XXX
1211
1212 optional arguments:
1213 -h, --help show this help message and exit
1214 --foo YYY
1215
1216Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001217attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1218by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001219
1220Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001221Providing a tuple to ``metavar`` specifies a different display for each of the
1222arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001223
1224 >>> parser = argparse.ArgumentParser(prog='PROG')
1225 >>> parser.add_argument('-x', nargs=2)
1226 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1227 >>> parser.print_help()
1228 usage: PROG [-h] [-x X X] [--foo bar baz]
1229
1230 optional arguments:
1231 -h, --help show this help message and exit
1232 -x X X
1233 --foo bar baz
1234
1235
1236dest
1237^^^^
1238
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001239Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001240object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1241attribute is determined by the ``dest`` keyword argument of
1242:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1243``dest`` is normally supplied as the first argument to
1244:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001245
1246 >>> parser = argparse.ArgumentParser()
1247 >>> parser.add_argument('bar')
Martin Panterf5e60482016-04-26 11:41:25 +00001248 >>> parser.parse_args(['XXX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001249 Namespace(bar='XXX')
1250
1251For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001252the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001253taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001254string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001255the first short option string by stripping the initial ``-`` character. Any
1256internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001257the string is a valid attribute name. The examples below illustrate this
1258behavior::
1259
1260 >>> parser = argparse.ArgumentParser()
1261 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1262 >>> parser.add_argument('-x', '-y')
1263 >>> parser.parse_args('-f 1 -x 2'.split())
1264 Namespace(foo_bar='1', x='2')
1265 >>> parser.parse_args('--foo 1 -y 2'.split())
1266 Namespace(foo_bar='1', x='2')
1267
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001268``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001269
1270 >>> parser = argparse.ArgumentParser()
1271 >>> parser.add_argument('--foo', dest='bar')
1272 >>> parser.parse_args('--foo XXX'.split())
1273 Namespace(bar='XXX')
1274
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001275Action classes
1276^^^^^^^^^^^^^^
1277
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001278Action classes implement the Action API, a callable which returns a callable
1279which processes arguments from the command-line. Any object which follows
1280this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001281:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001282
Terry Jan Reedyee558262014-08-23 22:21:47 -04001283.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1284 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001285 metavar=None)
1286
1287Action objects are used by an ArgumentParser to represent the information
1288needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001289command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001290plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001291except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001292
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001293Instances of Action (or return value of any callable to the ``action``
1294parameter) should have attributes "dest", "option_strings", "default", "type",
1295"required", "help", etc. defined. The easiest way to ensure these attributes
1296are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001297
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001298Action instances should be callable, so subclasses must override the
1299``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001300
1301* ``parser`` - The ArgumentParser object which contains this action.
1302
1303* ``namespace`` - The :class:`Namespace` object that will be returned by
1304 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1305 object using :func:`setattr`.
1306
1307* ``values`` - The associated command-line arguments, with any type conversions
1308 applied. Type conversions are specified with the type_ keyword argument to
1309 :meth:`~ArgumentParser.add_argument`.
1310
1311* ``option_string`` - The option string that was used to invoke this action.
1312 The ``option_string`` argument is optional, and will be absent if the action
1313 is associated with a positional argument.
1314
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001315The ``__call__`` method may perform arbitrary actions, but will typically set
1316attributes on the ``namespace`` based on ``dest`` and ``values``.
1317
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001318
1319The parse_args() method
1320-----------------------
1321
Georg Brandle0bf91d2010-10-17 10:34:28 +00001322.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001323
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001324 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001325 namespace. Return the populated namespace.
1326
1327 Previous calls to :meth:`add_argument` determine exactly what objects are
1328 created and how they are assigned. See the documentation for
1329 :meth:`add_argument` for details.
1330
R. David Murray0c7983e2017-09-04 16:17:26 -04001331 * args_ - List of strings to parse. The default is taken from
1332 :data:`sys.argv`.
1333
1334 * namespace_ - An object to take the attributes. The default is a new empty
1335 :class:`Namespace` object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001336
Georg Brandle0bf91d2010-10-17 10:34:28 +00001337
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001338Option value syntax
1339^^^^^^^^^^^^^^^^^^^
1340
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001341The :meth:`~ArgumentParser.parse_args` method supports several ways of
1342specifying the value of an option (if it takes one). In the simplest case, the
1343option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001344
1345 >>> parser = argparse.ArgumentParser(prog='PROG')
1346 >>> parser.add_argument('-x')
1347 >>> parser.add_argument('--foo')
Martin Panterf5e60482016-04-26 11:41:25 +00001348 >>> parser.parse_args(['-x', 'X'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001349 Namespace(foo=None, x='X')
Martin Panterf5e60482016-04-26 11:41:25 +00001350 >>> parser.parse_args(['--foo', 'FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001351 Namespace(foo='FOO', x=None)
1352
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001353For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001354and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001355separate them::
1356
Martin Panterf5e60482016-04-26 11:41:25 +00001357 >>> parser.parse_args(['--foo=FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001358 Namespace(foo='FOO', x=None)
1359
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001360For short options (options only one character long), the option and its value
1361can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001362
Martin Panterf5e60482016-04-26 11:41:25 +00001363 >>> parser.parse_args(['-xX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001364 Namespace(foo=None, x='X')
1365
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001366Several short options can be joined together, using only a single ``-`` prefix,
1367as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001368
1369 >>> parser = argparse.ArgumentParser(prog='PROG')
1370 >>> parser.add_argument('-x', action='store_true')
1371 >>> parser.add_argument('-y', action='store_true')
1372 >>> parser.add_argument('-z')
Martin Panterf5e60482016-04-26 11:41:25 +00001373 >>> parser.parse_args(['-xyzZ'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001374 Namespace(x=True, y=True, z='Z')
1375
1376
1377Invalid arguments
1378^^^^^^^^^^^^^^^^^
1379
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001380While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1381variety of errors, including ambiguous options, invalid types, invalid options,
1382wrong number of positional arguments, etc. When it encounters such an error,
1383it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001384
1385 >>> parser = argparse.ArgumentParser(prog='PROG')
1386 >>> parser.add_argument('--foo', type=int)
1387 >>> parser.add_argument('bar', nargs='?')
1388
1389 >>> # invalid type
1390 >>> parser.parse_args(['--foo', 'spam'])
1391 usage: PROG [-h] [--foo FOO] [bar]
1392 PROG: error: argument --foo: invalid int value: 'spam'
1393
1394 >>> # invalid option
1395 >>> parser.parse_args(['--bar'])
1396 usage: PROG [-h] [--foo FOO] [bar]
1397 PROG: error: no such option: --bar
1398
1399 >>> # wrong number of arguments
1400 >>> parser.parse_args(['spam', 'badger'])
1401 usage: PROG [-h] [--foo FOO] [bar]
1402 PROG: error: extra arguments found: badger
1403
1404
Éric Araujo543edbd2011-08-19 01:45:12 +02001405Arguments containing ``-``
1406^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001407
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001408The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1409the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001410ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001411attempt to specify an option or an attempt to provide a positional argument.
1412The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001413arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001414there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001415
1416 >>> parser = argparse.ArgumentParser(prog='PROG')
1417 >>> parser.add_argument('-x')
1418 >>> parser.add_argument('foo', nargs='?')
1419
1420 >>> # no negative number options, so -1 is a positional argument
1421 >>> parser.parse_args(['-x', '-1'])
1422 Namespace(foo=None, x='-1')
1423
1424 >>> # no negative number options, so -1 and -5 are positional arguments
1425 >>> parser.parse_args(['-x', '-1', '-5'])
1426 Namespace(foo='-5', x='-1')
1427
1428 >>> parser = argparse.ArgumentParser(prog='PROG')
1429 >>> parser.add_argument('-1', dest='one')
1430 >>> parser.add_argument('foo', nargs='?')
1431
1432 >>> # negative number options present, so -1 is an option
1433 >>> parser.parse_args(['-1', 'X'])
1434 Namespace(foo=None, one='X')
1435
1436 >>> # negative number options present, so -2 is an option
1437 >>> parser.parse_args(['-2'])
1438 usage: PROG [-h] [-1 ONE] [foo]
1439 PROG: error: no such option: -2
1440
1441 >>> # negative number options present, so both -1s are options
1442 >>> parser.parse_args(['-1', '-1'])
1443 usage: PROG [-h] [-1 ONE] [foo]
1444 PROG: error: argument -1: expected one argument
1445
Éric Araujo543edbd2011-08-19 01:45:12 +02001446If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001447like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001448:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1449argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001450
1451 >>> parser.parse_args(['--', '-f'])
1452 Namespace(foo='-f', one=None)
1453
Eli Benderskyf3114532013-12-02 05:49:54 -08001454.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001455
Eli Benderskyf3114532013-12-02 05:49:54 -08001456Argument abbreviations (prefix matching)
1457^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001458
Berker Peksag8089cd62015-02-14 01:39:17 +02001459The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>`
1460allows long options to be abbreviated to a prefix, if the abbreviation is
1461unambiguous (the prefix matches a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001462
1463 >>> parser = argparse.ArgumentParser(prog='PROG')
1464 >>> parser.add_argument('-bacon')
1465 >>> parser.add_argument('-badger')
1466 >>> parser.parse_args('-bac MMM'.split())
1467 Namespace(bacon='MMM', badger=None)
1468 >>> parser.parse_args('-bad WOOD'.split())
1469 Namespace(bacon=None, badger='WOOD')
1470 >>> parser.parse_args('-ba BA'.split())
1471 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1472 PROG: error: ambiguous option: -ba could match -badger, -bacon
1473
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001474An error is produced for arguments that could produce more than one options.
Berker Peksag8089cd62015-02-14 01:39:17 +02001475This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001476
R. David Murray0c7983e2017-09-04 16:17:26 -04001477.. _args:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001478
1479Beyond ``sys.argv``
1480^^^^^^^^^^^^^^^^^^^
1481
Éric Araujod9d7bca2011-08-10 04:19:03 +02001482Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001483of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001484:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1485interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001486
1487 >>> parser = argparse.ArgumentParser()
1488 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001489 ... 'integers', metavar='int', type=int, choices=range(10),
Serhiy Storchakadba90392016-05-10 12:01:23 +03001490 ... nargs='+', help='an integer in the range 0..9')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001491 >>> parser.add_argument(
1492 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001493 ... default=max, help='sum the integers (default: find the max)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001494 >>> parser.parse_args(['1', '2', '3', '4'])
1495 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panterf5e60482016-04-26 11:41:25 +00001496 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001497 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1498
R. David Murray0c7983e2017-09-04 16:17:26 -04001499.. _namespace:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001500
Steven Bethardd8f2d502011-03-26 19:50:06 +01001501The Namespace object
1502^^^^^^^^^^^^^^^^^^^^
1503
Éric Araujo63b18a42011-07-29 17:59:17 +02001504.. class:: Namespace
1505
1506 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1507 an object holding attributes and return it.
1508
1509This class is deliberately simple, just an :class:`object` subclass with a
1510readable string representation. If you prefer to have dict-like view of the
1511attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001512
1513 >>> parser = argparse.ArgumentParser()
1514 >>> parser.add_argument('--foo')
1515 >>> args = parser.parse_args(['--foo', 'BAR'])
1516 >>> vars(args)
1517 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001518
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001519It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001520already existing object, rather than a new :class:`Namespace` object. This can
1521be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001522
Éric Araujo28053fb2010-11-22 03:09:19 +00001523 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001524 ... pass
1525 ...
1526 >>> c = C()
1527 >>> parser = argparse.ArgumentParser()
1528 >>> parser.add_argument('--foo')
1529 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1530 >>> c.foo
1531 'BAR'
1532
1533
1534Other utilities
1535---------------
1536
1537Sub-commands
1538^^^^^^^^^^^^
1539
Georg Brandlfc9a1132013-10-06 18:51:39 +02001540.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1541 [parser_class], [action], \
Anthony Sottilecc182582018-08-23 20:08:54 -07001542 [option_string], [dest], [required], \
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001543 [help], [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001544
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001545 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001546 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001547 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001548 this way can be a particularly good idea when a program performs several
1549 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001550 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001551 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001552 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001553 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1554 command name and any :class:`ArgumentParser` constructor arguments, and
1555 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001556
Georg Brandlfc9a1132013-10-06 18:51:39 +02001557 Description of parameters:
1558
1559 * title - title for the sub-parser group in help output; by default
1560 "subcommands" if description is provided, otherwise uses title for
1561 positional arguments
1562
1563 * description - description for the sub-parser group in help output, by
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001564 default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001565
1566 * prog - usage information that will be displayed with sub-command help,
1567 by default the name of the program and any positional arguments before the
1568 subparser argument
1569
1570 * parser_class - class which will be used to create sub-parser instances, by
1571 default the class of the current parser (e.g. ArgumentParser)
1572
Berker Peksag5a494f62015-01-20 06:45:53 +02001573 * action_ - the basic type of action to be taken when this argument is
1574 encountered at the command line
1575
1576 * dest_ - name of the attribute under which sub-command name will be
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001577 stored; by default ``None`` and no value is stored
Georg Brandlfc9a1132013-10-06 18:51:39 +02001578
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001579 * required_ - Whether or not a subcommand must be provided, by default
Ned Deily8ebf5ce2018-05-23 21:55:15 -04001580 ``False``.
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001581
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001582 * help_ - help for sub-parser group in help output, by default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001583
Berker Peksag5a494f62015-01-20 06:45:53 +02001584 * metavar_ - string presenting available sub-commands in help; by default it
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001585 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
Georg Brandlfc9a1132013-10-06 18:51:39 +02001586
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001587 Some example usage::
1588
1589 >>> # create the top-level parser
1590 >>> parser = argparse.ArgumentParser(prog='PROG')
1591 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1592 >>> subparsers = parser.add_subparsers(help='sub-command help')
1593 >>>
1594 >>> # create the parser for the "a" command
1595 >>> parser_a = subparsers.add_parser('a', help='a help')
1596 >>> parser_a.add_argument('bar', type=int, help='bar help')
1597 >>>
1598 >>> # create the parser for the "b" command
1599 >>> parser_b = subparsers.add_parser('b', help='b help')
1600 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1601 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001602 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001603 >>> parser.parse_args(['a', '12'])
1604 Namespace(bar=12, foo=False)
1605 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1606 Namespace(baz='Z', foo=True)
1607
1608 Note that the object returned by :meth:`parse_args` will only contain
1609 attributes for the main parser and the subparser that was selected by the
1610 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001611 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1612 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001613 ``baz`` attributes are present.
1614
1615 Similarly, when a help message is requested from a subparser, only the help
1616 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001617 include parent parser or sibling parser messages. (A help message for each
1618 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001619 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001620
1621 ::
1622
1623 >>> parser.parse_args(['--help'])
1624 usage: PROG [-h] [--foo] {a,b} ...
1625
1626 positional arguments:
1627 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001628 a a help
1629 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001630
1631 optional arguments:
1632 -h, --help show this help message and exit
1633 --foo foo help
1634
1635 >>> parser.parse_args(['a', '--help'])
1636 usage: PROG a [-h] bar
1637
1638 positional arguments:
1639 bar bar help
1640
1641 optional arguments:
1642 -h, --help show this help message and exit
1643
1644 >>> parser.parse_args(['b', '--help'])
1645 usage: PROG b [-h] [--baz {X,Y,Z}]
1646
1647 optional arguments:
1648 -h, --help show this help message and exit
1649 --baz {X,Y,Z} baz help
1650
1651 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1652 keyword arguments. When either is present, the subparser's commands will
1653 appear in their own group in the help output. For example::
1654
1655 >>> parser = argparse.ArgumentParser()
1656 >>> subparsers = parser.add_subparsers(title='subcommands',
1657 ... description='valid subcommands',
1658 ... help='additional help')
1659 >>> subparsers.add_parser('foo')
1660 >>> subparsers.add_parser('bar')
1661 >>> parser.parse_args(['-h'])
1662 usage: [-h] {foo,bar} ...
1663
1664 optional arguments:
1665 -h, --help show this help message and exit
1666
1667 subcommands:
1668 valid subcommands
1669
1670 {foo,bar} additional help
1671
Steven Bethardfd311a72010-12-18 11:19:23 +00001672 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1673 which allows multiple strings to refer to the same subparser. This example,
1674 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1675
1676 >>> parser = argparse.ArgumentParser()
1677 >>> subparsers = parser.add_subparsers()
1678 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1679 >>> checkout.add_argument('foo')
1680 >>> parser.parse_args(['co', 'bar'])
1681 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001682
1683 One particularly effective way of handling sub-commands is to combine the use
1684 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1685 that each subparser knows which Python function it should execute. For
1686 example::
1687
1688 >>> # sub-command functions
1689 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001690 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001691 ...
1692 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001693 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001694 ...
1695 >>> # create the top-level parser
1696 >>> parser = argparse.ArgumentParser()
1697 >>> subparsers = parser.add_subparsers()
1698 >>>
1699 >>> # create the parser for the "foo" command
1700 >>> parser_foo = subparsers.add_parser('foo')
1701 >>> parser_foo.add_argument('-x', type=int, default=1)
1702 >>> parser_foo.add_argument('y', type=float)
1703 >>> parser_foo.set_defaults(func=foo)
1704 >>>
1705 >>> # create the parser for the "bar" command
1706 >>> parser_bar = subparsers.add_parser('bar')
1707 >>> parser_bar.add_argument('z')
1708 >>> parser_bar.set_defaults(func=bar)
1709 >>>
1710 >>> # parse the args and call whatever function was selected
1711 >>> args = parser.parse_args('foo 1 -x 2'.split())
1712 >>> args.func(args)
1713 2.0
1714 >>>
1715 >>> # parse the args and call whatever function was selected
1716 >>> args = parser.parse_args('bar XYZYX'.split())
1717 >>> args.func(args)
1718 ((XYZYX))
1719
Steven Bethardfd311a72010-12-18 11:19:23 +00001720 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001721 appropriate function after argument parsing is complete. Associating
1722 functions with actions like this is typically the easiest way to handle the
1723 different actions for each of your subparsers. However, if it is necessary
1724 to check the name of the subparser that was invoked, the ``dest`` keyword
1725 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001726
1727 >>> parser = argparse.ArgumentParser()
1728 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1729 >>> subparser1 = subparsers.add_parser('1')
1730 >>> subparser1.add_argument('-x')
1731 >>> subparser2 = subparsers.add_parser('2')
1732 >>> subparser2.add_argument('y')
1733 >>> parser.parse_args(['2', 'frobble'])
1734 Namespace(subparser_name='2', y='frobble')
1735
1736
1737FileType objects
1738^^^^^^^^^^^^^^^^
1739
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001740.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001741
1742 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001743 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001744 :class:`FileType` objects as their type will open command-line arguments as
1745 files with the requested modes, buffer sizes, encodings and error handling
1746 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001747
Éric Araujoc3ef0372012-02-20 01:44:55 +01001748 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001749 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1750 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1751 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1752 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 +00001753
1754 FileType objects understand the pseudo-argument ``'-'`` and automatically
1755 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001756 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001757
Éric Araujoc3ef0372012-02-20 01:44:55 +01001758 >>> parser = argparse.ArgumentParser()
1759 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1760 >>> parser.parse_args(['-'])
1761 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001762
R David Murrayfced3ec2013-12-31 11:18:01 -05001763 .. versionadded:: 3.4
1764 The *encodings* and *errors* keyword arguments.
1765
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001766
1767Argument groups
1768^^^^^^^^^^^^^^^
1769
Georg Brandle0bf91d2010-10-17 10:34:28 +00001770.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001771
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001772 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001773 "positional arguments" and "optional arguments" when displaying help
1774 messages. When there is a better conceptual grouping of arguments than this
1775 default one, appropriate groups can be created using the
1776 :meth:`add_argument_group` method::
1777
1778 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1779 >>> group = parser.add_argument_group('group')
1780 >>> group.add_argument('--foo', help='foo help')
1781 >>> group.add_argument('bar', help='bar help')
1782 >>> parser.print_help()
1783 usage: PROG [--foo FOO] bar
1784
1785 group:
1786 bar bar help
1787 --foo FOO foo help
1788
1789 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001790 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1791 :class:`ArgumentParser`. When an argument is added to the group, the parser
1792 treats it just like a normal argument, but displays the argument in a
1793 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001794 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001795 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001796
1797 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1798 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1799 >>> group1.add_argument('foo', help='foo help')
1800 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1801 >>> group2.add_argument('--bar', help='bar help')
1802 >>> parser.print_help()
1803 usage: PROG [--bar BAR] foo
1804
1805 group1:
1806 group1 description
1807
1808 foo foo help
1809
1810 group2:
1811 group2 description
1812
1813 --bar BAR bar help
1814
Sandro Tosi99e7d072012-03-26 19:36:23 +02001815 Note that any arguments not in your user-defined groups will end up back
1816 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001817
1818
1819Mutual exclusion
1820^^^^^^^^^^^^^^^^
1821
Georg Brandled86ff82013-10-06 13:09:59 +02001822.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001823
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001824 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1825 one of the arguments in the mutually exclusive group was present on the
1826 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001827
1828 >>> parser = argparse.ArgumentParser(prog='PROG')
1829 >>> group = parser.add_mutually_exclusive_group()
1830 >>> group.add_argument('--foo', action='store_true')
1831 >>> group.add_argument('--bar', action='store_false')
1832 >>> parser.parse_args(['--foo'])
1833 Namespace(bar=True, foo=True)
1834 >>> parser.parse_args(['--bar'])
1835 Namespace(bar=False, foo=False)
1836 >>> parser.parse_args(['--foo', '--bar'])
1837 usage: PROG [-h] [--foo | --bar]
1838 PROG: error: argument --bar: not allowed with argument --foo
1839
Georg Brandle0bf91d2010-10-17 10:34:28 +00001840 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001841 argument, to indicate that at least one of the mutually exclusive arguments
1842 is required::
1843
1844 >>> parser = argparse.ArgumentParser(prog='PROG')
1845 >>> group = parser.add_mutually_exclusive_group(required=True)
1846 >>> group.add_argument('--foo', action='store_true')
1847 >>> group.add_argument('--bar', action='store_false')
1848 >>> parser.parse_args([])
1849 usage: PROG [-h] (--foo | --bar)
1850 PROG: error: one of the arguments --foo --bar is required
1851
1852 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001853 *title* and *description* arguments of
1854 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001855
1856
1857Parser defaults
1858^^^^^^^^^^^^^^^
1859
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001860.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001861
1862 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001863 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001864 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001865 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001866 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001867
1868 >>> parser = argparse.ArgumentParser()
1869 >>> parser.add_argument('foo', type=int)
1870 >>> parser.set_defaults(bar=42, baz='badger')
1871 >>> parser.parse_args(['736'])
1872 Namespace(bar=42, baz='badger', foo=736)
1873
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001874 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001875
1876 >>> parser = argparse.ArgumentParser()
1877 >>> parser.add_argument('--foo', default='bar')
1878 >>> parser.set_defaults(foo='spam')
1879 >>> parser.parse_args([])
1880 Namespace(foo='spam')
1881
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001882 Parser-level defaults can be particularly useful when working with multiple
1883 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1884 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001885
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001886.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001887
1888 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001889 :meth:`~ArgumentParser.add_argument` or by
1890 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001891
1892 >>> parser = argparse.ArgumentParser()
1893 >>> parser.add_argument('--foo', default='badger')
1894 >>> parser.get_default('foo')
1895 'badger'
1896
1897
1898Printing help
1899^^^^^^^^^^^^^
1900
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001901In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1902care of formatting and printing any usage or error messages. However, several
1903formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001904
Georg Brandle0bf91d2010-10-17 10:34:28 +00001905.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001906
1907 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001908 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001909 assumed.
1910
Georg Brandle0bf91d2010-10-17 10:34:28 +00001911.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001912
1913 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001914 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001915 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001916
1917There are also variants of these methods that simply return a string instead of
1918printing it:
1919
Georg Brandle0bf91d2010-10-17 10:34:28 +00001920.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001921
1922 Return a string containing a brief description of how the
1923 :class:`ArgumentParser` should be invoked on the command line.
1924
Georg Brandle0bf91d2010-10-17 10:34:28 +00001925.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001926
1927 Return a string containing a help message, including the program usage and
1928 information about the arguments registered with the :class:`ArgumentParser`.
1929
1930
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001931Partial parsing
1932^^^^^^^^^^^^^^^
1933
Georg Brandle0bf91d2010-10-17 10:34:28 +00001934.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001935
Georg Brandl69518bc2011-04-16 16:44:54 +02001936Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001937the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001938:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001939:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1940extra arguments are present. Instead, it returns a two item tuple containing
1941the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001942
1943::
1944
1945 >>> parser = argparse.ArgumentParser()
1946 >>> parser.add_argument('--foo', action='store_true')
1947 >>> parser.add_argument('bar')
1948 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1949 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1950
Eli Benderskyf3114532013-12-02 05:49:54 -08001951.. warning::
1952 :ref:`Prefix matching <prefix-matching>` rules apply to
1953 :meth:`parse_known_args`. The parser may consume an option even if it's just
1954 a prefix of one of its known options, instead of leaving it in the remaining
1955 arguments list.
1956
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001957
1958Customizing file parsing
1959^^^^^^^^^^^^^^^^^^^^^^^^
1960
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001961.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001962
Georg Brandle0bf91d2010-10-17 10:34:28 +00001963 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001964 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft8b852f12014-05-20 12:58:38 -04001965 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001966 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001967
Georg Brandle0bf91d2010-10-17 10:34:28 +00001968 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001969 the argument file. It returns a list of arguments parsed from this string.
1970 The method is called once per line read from the argument file, in order.
1971
1972 A useful override of this method is one that treats each space-separated word
Berker Peksag5493e472016-10-17 06:14:17 +03001973 as an argument. The following example demonstrates how to do this::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001974
Berker Peksag5493e472016-10-17 06:14:17 +03001975 class MyArgumentParser(argparse.ArgumentParser):
1976 def convert_arg_line_to_args(self, arg_line):
1977 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001978
1979
Georg Brandl93754922010-10-17 10:28:04 +00001980Exiting methods
1981^^^^^^^^^^^^^^^
1982
1983.. method:: ArgumentParser.exit(status=0, message=None)
1984
1985 This method terminates the program, exiting with the specified *status*
1986 and, if given, it prints a *message* before that.
1987
1988.. method:: ArgumentParser.error(message)
1989
1990 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001991 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001992
R. David Murray0f6b9d22017-09-06 20:25:40 -04001993
1994Intermixed parsing
1995^^^^^^^^^^^^^^^^^^
1996
1997.. method:: ArgumentParser.parse_intermixed_args(args=None, namespace=None)
1998.. method:: ArgumentParser.parse_known_intermixed_args(args=None, namespace=None)
1999
2000A number of Unix commands allow the user to intermix optional arguments with
2001positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args`
2002and :meth:`~ArgumentParser.parse_known_intermixed_args` methods
2003support this parsing style.
2004
2005These parsers do not support all the argparse features, and will raise
2006exceptions if unsupported features are used. In particular, subparsers,
2007``argparse.REMAINDER``, and mutually exclusive groups that include both
2008optionals and positionals are not supported.
2009
2010The following example shows the difference between
2011:meth:`~ArgumentParser.parse_known_args` and
2012:meth:`~ArgumentParser.parse_intermixed_args`: the former returns ``['2',
2013'3']`` as unparsed arguments, while the latter collects all the positionals
2014into ``rest``. ::
2015
2016 >>> parser = argparse.ArgumentParser()
2017 >>> parser.add_argument('--foo')
2018 >>> parser.add_argument('cmd')
2019 >>> parser.add_argument('rest', nargs='*', type=int)
2020 >>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
2021 (Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
2022 >>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
2023 Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])
2024
2025:meth:`~ArgumentParser.parse_known_intermixed_args` returns a two item tuple
2026containing the populated namespace and the list of remaining argument strings.
2027:meth:`~ArgumentParser.parse_intermixed_args` raises an error if there are any
2028remaining unparsed argument strings.
2029
2030.. versionadded:: 3.7
2031
Raymond Hettinger677e10a2010-12-07 06:45:30 +00002032.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00002033
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002034Upgrading optparse code
2035-----------------------
2036
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002037Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002038with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
2039transparently, particularly with the changes required to support the new
2040``nargs=`` specifiers and better usage messages. When most everything in
2041:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
2042longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002043
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03002044The :mod:`argparse` module improves on the standard library :mod:`optparse`
2045module in a number of ways including:
2046
2047* Handling positional arguments.
2048* Supporting sub-commands.
2049* Allowing alternative option prefixes like ``+`` and ``/``.
2050* Handling zero-or-more and one-or-more style arguments.
2051* Producing more informative usage messages.
2052* Providing a much simpler interface for custom ``type`` and ``action``.
2053
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002054A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002055
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002056* Replace all :meth:`optparse.OptionParser.add_option` calls with
2057 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002058
R David Murray5e0c5712012-03-30 18:07:42 -04002059* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00002060 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04002061 calls for the positional arguments. Keep in mind that what was previously
R. David Murray0c7983e2017-09-04 16:17:26 -04002062 called ``options``, now in the :mod:`argparse` context is called ``args``.
2063
2064* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
R. David Murray0f6b9d22017-09-06 20:25:40 -04002065 by using :meth:`~ArgumentParser.parse_intermixed_args` instead of
2066 :meth:`~ArgumentParser.parse_args`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002067
2068* Replace callback actions and the ``callback_*`` keyword arguments with
2069 ``type`` or ``action`` arguments.
2070
2071* Replace string names for ``type`` keyword arguments with the corresponding
2072 type objects (e.g. int, float, complex, etc).
2073
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002074* Replace :class:`optparse.Values` with :class:`Namespace` and
2075 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
2076 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002077
2078* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03002079 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002080 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00002081
2082* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panterd21e0b52015-10-10 10:36:22 +00002083 ``parser.add_argument('--version', action='version', version='<the version>')``.