blob: 45303048174dfabf5437b26da90f415d5af1cc33 [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,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000429including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000430
Steven Bethard0331e902011-03-26 14:48:04 +0100431:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
432default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000433
434 >>> parser = argparse.ArgumentParser(
435 ... prog='PROG',
436 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
437 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
438 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
439 >>> parser.print_help()
440 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
441
442 positional arguments:
443 bar BAR! (default: [1, 2, 3])
444
445 optional arguments:
446 -h, --help show this help message and exit
447 --foo FOO FOO! (default: 42)
448
Steven Bethard0331e902011-03-26 14:48:04 +0100449:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300450argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100451as the regular formatter does)::
452
453 >>> parser = argparse.ArgumentParser(
454 ... prog='PROG',
455 ... formatter_class=argparse.MetavarTypeHelpFormatter)
456 >>> parser.add_argument('--foo', type=int)
457 >>> parser.add_argument('bar', type=float)
458 >>> parser.print_help()
459 usage: PROG [-h] [--foo int] float
460
461 positional arguments:
462 float
463
464 optional arguments:
465 -h, --help show this help message and exit
466 --foo int
467
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000468
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300469prefix_chars
470^^^^^^^^^^^^
471
472Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
473Parsers that need to support different or additional prefix
474characters, e.g. for options
475like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
476to the ArgumentParser constructor::
477
478 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
479 >>> parser.add_argument('+f')
480 >>> parser.add_argument('++bar')
481 >>> parser.parse_args('+f X ++bar Y'.split())
482 Namespace(bar='Y', f='X')
483
484The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
485characters that does not include ``-`` will cause ``-f/--foo`` options to be
486disallowed.
487
488
489fromfile_prefix_chars
490^^^^^^^^^^^^^^^^^^^^^
491
492Sometimes, for example when dealing with a particularly long argument lists, it
493may make sense to keep the list of arguments in a file rather than typing it out
494at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
495:class:`ArgumentParser` constructor, then arguments that start with any of the
496specified characters will be treated as files, and will be replaced by the
497arguments they contain. For example::
498
499 >>> with open('args.txt', 'w') as fp:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300500 ... fp.write('-f\nbar')
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300501 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
502 >>> parser.add_argument('-f')
503 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
504 Namespace(f='bar')
505
506Arguments read from a file must by default be one per line (but see also
507:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
508were in the same place as the original file referencing argument on the command
509line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
510is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
511
512The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
513arguments will never be treated as file references.
514
515
516argument_default
517^^^^^^^^^^^^^^^^
518
519Generally, argument defaults are specified either by passing a default to
520:meth:`~ArgumentParser.add_argument` or by calling the
521:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
522pairs. Sometimes however, it may be useful to specify a single parser-wide
523default for arguments. This can be accomplished by passing the
524``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
525to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
526calls, we supply ``argument_default=SUPPRESS``::
527
528 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
529 >>> parser.add_argument('--foo')
530 >>> parser.add_argument('bar', nargs='?')
531 >>> parser.parse_args(['--foo', '1', 'BAR'])
532 Namespace(bar='BAR', foo='1')
533 >>> parser.parse_args([])
534 Namespace()
535
Berker Peksag8089cd62015-02-14 01:39:17 +0200536.. _allow_abbrev:
537
538allow_abbrev
539^^^^^^^^^^^^
540
541Normally, when you pass an argument list to the
Martin Panterd2ad5712015-11-02 04:20:33 +0000542:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`,
Berker Peksag8089cd62015-02-14 01:39:17 +0200543it :ref:`recognizes abbreviations <prefix-matching>` of long options.
544
545This feature can be disabled by setting ``allow_abbrev`` to ``False``::
546
547 >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
548 >>> parser.add_argument('--foobar', action='store_true')
549 >>> parser.add_argument('--foonley', action='store_false')
Berker Peksage7e497b2015-03-12 20:47:41 +0200550 >>> parser.parse_args(['--foon'])
Berker Peksag8089cd62015-02-14 01:39:17 +0200551 usage: PROG [-h] [--foobar] [--foonley]
552 PROG: error: unrecognized arguments: --foon
553
554.. versionadded:: 3.5
555
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300556
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000557conflict_handler
558^^^^^^^^^^^^^^^^
559
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000560:class:`ArgumentParser` objects do not allow two actions with the same option
Martin Panter0f0eac42016-09-07 11:04:41 +0000561string. By default, :class:`ArgumentParser` objects raise an exception if an
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000562attempt is made to create an argument with an option string that is already in
563use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000564
565 >>> parser = argparse.ArgumentParser(prog='PROG')
566 >>> parser.add_argument('-f', '--foo', help='old foo help')
567 >>> parser.add_argument('--foo', help='new foo help')
568 Traceback (most recent call last):
569 ..
570 ArgumentError: argument --foo: conflicting option string(s): --foo
571
572Sometimes (e.g. when using parents_) it may be useful to simply override any
573older arguments with the same option string. To get this behavior, the value
574``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000575:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000576
577 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
578 >>> parser.add_argument('-f', '--foo', help='old foo help')
579 >>> parser.add_argument('--foo', help='new foo help')
580 >>> parser.print_help()
581 usage: PROG [-h] [-f FOO] [--foo FOO]
582
583 optional arguments:
584 -h, --help show this help message and exit
585 -f FOO old foo help
586 --foo FOO new foo help
587
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000588Note that :class:`ArgumentParser` objects only remove an action if all of its
589option strings are overridden. So, in the example above, the old ``-f/--foo``
590action is retained as the ``-f`` action, because only the ``--foo`` option
591string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000592
593
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300594add_help
595^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000596
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300597By default, ArgumentParser objects add an option which simply displays
598the parser's help message. For example, consider a file named
599``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000600
601 import argparse
602 parser = argparse.ArgumentParser()
603 parser.add_argument('--foo', help='foo help')
604 args = parser.parse_args()
605
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300606If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Martin Panter1050d2d2016-07-26 11:18:21 +0200607help will be printed:
608
609.. code-block:: shell-session
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000610
611 $ python myprogram.py --help
612 usage: myprogram.py [-h] [--foo FOO]
613
614 optional arguments:
615 -h, --help show this help message and exit
616 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000617
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300618Occasionally, it may be useful to disable the addition of this help option.
619This can be achieved by passing ``False`` as the ``add_help=`` argument to
620:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000621
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300622 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
623 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000624 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300625 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000626
627 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300628 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000629
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300630The help option is typically ``-h/--help``. The exception to this is
631if the ``prefix_chars=`` is specified and does not include ``-``, in
632which case ``-h`` and ``--help`` are not valid options. In
633this case, the first character in ``prefix_chars`` is used to prefix
634the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000635
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300636 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000637 >>> parser.print_help()
Georg Brandld2914ce2013-10-06 09:50:36 +0200638 usage: PROG [+h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000639
640 optional arguments:
Georg Brandld2914ce2013-10-06 09:50:36 +0200641 +h, ++help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000642
643
644The add_argument() method
645-------------------------
646
Georg Brandlc9007082011-01-09 09:04:08 +0000647.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
648 [const], [default], [type], [choices], [required], \
649 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000650
Georg Brandl69518bc2011-04-16 16:44:54 +0200651 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000652 has its own more detailed description below, but in short they are:
653
654 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300655 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000656
657 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200658 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000659
660 * nargs_ - The number of command-line arguments that should be consumed.
661
662 * const_ - A constant value required by some action_ and nargs_ selections.
663
664 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200665 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000666
Ezio Melotti2409d772011-04-16 23:13:50 +0300667 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000668
669 * choices_ - A container of the allowable values for the argument.
670
671 * required_ - Whether or not the command-line option may be omitted
672 (optionals only).
673
674 * help_ - A brief description of what the argument does.
675
676 * metavar_ - A name for the argument in usage messages.
677
678 * dest_ - The name of the attribute to be added to the object returned by
679 :meth:`parse_args`.
680
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000681The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000682
Georg Brandle0bf91d2010-10-17 10:34:28 +0000683
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000684name or flags
685^^^^^^^^^^^^^
686
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300687The :meth:`~ArgumentParser.add_argument` method must know whether an optional
688argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
689filenames, is expected. The first arguments passed to
690:meth:`~ArgumentParser.add_argument` must therefore be either a series of
691flags, or a simple argument name. For example, an optional argument could
692be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000693
694 >>> parser.add_argument('-f', '--foo')
695
696while a positional argument could be created like::
697
698 >>> parser.add_argument('bar')
699
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300700When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
701identified by the ``-`` prefix, and the remaining arguments will be assumed to
702be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000703
704 >>> parser = argparse.ArgumentParser(prog='PROG')
705 >>> parser.add_argument('-f', '--foo')
706 >>> parser.add_argument('bar')
707 >>> parser.parse_args(['BAR'])
708 Namespace(bar='BAR', foo=None)
709 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
710 Namespace(bar='BAR', foo='FOO')
711 >>> parser.parse_args(['--foo', 'FOO'])
712 usage: PROG [-h] [-f FOO] bar
713 PROG: error: too few arguments
714
Georg Brandle0bf91d2010-10-17 10:34:28 +0000715
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000716action
717^^^^^^
718
Éric Araujod9d7bca2011-08-10 04:19:03 +0200719:class:`ArgumentParser` objects associate command-line arguments with actions. These
720actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000721them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300722:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -0500723how the command-line arguments should be handled. The supplied actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000724
725* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300726 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000727
728 >>> parser = argparse.ArgumentParser()
729 >>> parser.add_argument('--foo')
730 >>> parser.parse_args('--foo 1'.split())
731 Namespace(foo='1')
732
733* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panterb4912b82016-04-09 03:49:48 +0000734 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300735 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000736
737 >>> parser = argparse.ArgumentParser()
738 >>> parser.add_argument('--foo', action='store_const', const=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000739 >>> parser.parse_args(['--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000740 Namespace(foo=42)
741
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800742* ``'store_true'`` and ``'store_false'`` - These are special cases of
743 ``'store_const'`` used for storing the values ``True`` and ``False``
744 respectively. In addition, they create default values of ``False`` and
745 ``True`` respectively. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000746
747 >>> parser = argparse.ArgumentParser()
748 >>> parser.add_argument('--foo', action='store_true')
749 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800750 >>> parser.add_argument('--baz', action='store_false')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000751 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800752 Namespace(foo=True, bar=False, baz=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000753
754* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000755 list. This is useful to allow an option to be specified multiple times.
756 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000757
758 >>> parser = argparse.ArgumentParser()
759 >>> parser.add_argument('--foo', action='append')
760 >>> parser.parse_args('--foo 1 --foo 2'.split())
761 Namespace(foo=['1', '2'])
762
763* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000764 the const_ keyword argument to the list. (Note that the const_ keyword
765 argument defaults to ``None``.) The ``'append_const'`` action is typically
766 useful when multiple arguments need to store constants to the same list. For
767 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000768
769 >>> parser = argparse.ArgumentParser()
770 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
771 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
772 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200773 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000774
Sandro Tosi98492a52012-01-04 23:25:04 +0100775* ``'count'`` - This counts the number of times a keyword argument occurs. For
776 example, this is useful for increasing verbosity levels::
777
778 >>> parser = argparse.ArgumentParser()
779 >>> parser.add_argument('--verbose', '-v', action='count')
Martin Panterf5e60482016-04-26 11:41:25 +0000780 >>> parser.parse_args(['-vvv'])
Sandro Tosi98492a52012-01-04 23:25:04 +0100781 Namespace(verbose=3)
782
783* ``'help'`` - This prints a complete help message for all the options in the
784 current parser and then exits. By default a help action is automatically
785 added to the parser. See :class:`ArgumentParser` for details of how the
786 output is created.
787
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000788* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300789 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100790 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000791
792 >>> import argparse
793 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000794 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
795 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000796 PROG 2.0
797
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400798You may also specify an arbitrary action by passing an Action subclass or
799other object that implements the same interface. The recommended way to do
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400800this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400801and optionally the ``__init__`` method.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000802
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000803An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000804
805 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400806 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
807 ... if nargs is not None:
808 ... raise ValueError("nargs not allowed")
809 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000810 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000811 ... print('%r %r %r' % (namespace, values, option_string))
812 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000813 ...
814 >>> parser = argparse.ArgumentParser()
815 >>> parser.add_argument('--foo', action=FooAction)
816 >>> parser.add_argument('bar', action=FooAction)
817 >>> args = parser.parse_args('1 --foo 2'.split())
818 Namespace(bar=None, foo=None) '1' None
819 Namespace(bar='1', foo=None) '2' '--foo'
820 >>> args
821 Namespace(bar='1', foo='2')
822
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400823For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000824
825nargs
826^^^^^
827
828ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000829single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300830different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000831values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000832
Éric Araujoc3ef0372012-02-20 01:44:55 +0100833* ``N`` (an integer). ``N`` arguments from the command line will be gathered
834 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000835
Georg Brandl682d7e02010-10-06 10:26:05 +0000836 >>> parser = argparse.ArgumentParser()
837 >>> parser.add_argument('--foo', nargs=2)
838 >>> parser.add_argument('bar', nargs=1)
839 >>> parser.parse_args('c --foo a b'.split())
840 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000841
Georg Brandl682d7e02010-10-06 10:26:05 +0000842 Note that ``nargs=1`` produces a list of one item. This is different from
843 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000844
Éric Araujofde92422011-08-19 01:30:26 +0200845* ``'?'``. One argument will be consumed from the command line if possible, and
846 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000847 default_ will be produced. Note that for optional arguments, there is an
848 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200849 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000850 examples to illustrate this::
851
852 >>> parser = argparse.ArgumentParser()
853 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
854 >>> parser.add_argument('bar', nargs='?', default='d')
Martin Panterf5e60482016-04-26 11:41:25 +0000855 >>> parser.parse_args(['XX', '--foo', 'YY'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000856 Namespace(bar='XX', foo='YY')
Martin Panterf5e60482016-04-26 11:41:25 +0000857 >>> parser.parse_args(['XX', '--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000858 Namespace(bar='XX', foo='c')
Martin Panterf5e60482016-04-26 11:41:25 +0000859 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000860 Namespace(bar='d', foo='d')
861
862 One of the more common uses of ``nargs='?'`` is to allow optional input and
863 output files::
864
865 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000866 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
867 ... default=sys.stdin)
868 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
869 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000870 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000871 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
872 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000873 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000874 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
875 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000876
Éric Araujod9d7bca2011-08-10 04:19:03 +0200877* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000878 it generally doesn't make much sense to have more than one positional argument
879 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
880 possible. For example::
881
882 >>> parser = argparse.ArgumentParser()
883 >>> parser.add_argument('--foo', nargs='*')
884 >>> parser.add_argument('--bar', nargs='*')
885 >>> parser.add_argument('baz', nargs='*')
886 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
887 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
888
889* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
890 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200891 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000892
893 >>> parser = argparse.ArgumentParser(prog='PROG')
894 >>> parser.add_argument('foo', nargs='+')
Martin Panterf5e60482016-04-26 11:41:25 +0000895 >>> parser.parse_args(['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000896 Namespace(foo=['a', 'b'])
Martin Panterf5e60482016-04-26 11:41:25 +0000897 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000898 usage: PROG [-h] foo [foo ...]
899 PROG: error: too few arguments
900
Sandro Tosida8e11a2012-01-19 22:23:00 +0100901* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
902 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100903 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100904
905 >>> parser = argparse.ArgumentParser(prog='PROG')
906 >>> parser.add_argument('--foo')
907 >>> parser.add_argument('command')
908 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100909 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100910 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100911
Éric Araujod9d7bca2011-08-10 04:19:03 +0200912If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200913is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000914will be consumed and a single item (not a list) will be produced.
915
916
917const
918^^^^^
919
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300920The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
921constant values that are not read from the command line but are required for
922the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000923
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300924* When :meth:`~ArgumentParser.add_argument` is called with
925 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100926 ``const`` value to one of the attributes of the object returned by
927 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000928
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300929* When :meth:`~ArgumentParser.add_argument` is called with option strings
930 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200931 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300932 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200933 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300934 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000935
Martin Panterb4912b82016-04-09 03:49:48 +0000936With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panter119e5022016-04-16 09:28:57 +0000937keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000938
939
940default
941^^^^^^^
942
943All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300944command line. The ``default`` keyword argument of
945:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200946specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300947For optional arguments, the ``default`` value is used when the option string
948was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000949
950 >>> parser = argparse.ArgumentParser()
951 >>> parser.add_argument('--foo', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000952 >>> parser.parse_args(['--foo', '2'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000953 Namespace(foo='2')
Martin Panterf5e60482016-04-26 11:41:25 +0000954 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000955 Namespace(foo=42)
956
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400957If the ``default`` value is a string, the parser parses the value as if it
958were a command-line argument. In particular, the parser applies any type_
959conversion argument, if provided, before setting the attribute on the
960:class:`Namespace` return value. Otherwise, the parser uses the value as is::
961
962 >>> parser = argparse.ArgumentParser()
963 >>> parser.add_argument('--length', default='10', type=int)
964 >>> parser.add_argument('--width', default=10.5, type=int)
965 >>> parser.parse_args()
966 Namespace(length=10, width=10.5)
967
Éric Araujo543edbd2011-08-19 01:45:12 +0200968For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200969is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000970
971 >>> parser = argparse.ArgumentParser()
972 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000973 >>> parser.parse_args(['a'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000974 Namespace(foo='a')
Martin Panterf5e60482016-04-26 11:41:25 +0000975 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000976 Namespace(foo=42)
977
978
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000979Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
980command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000981
982 >>> parser = argparse.ArgumentParser()
983 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
984 >>> parser.parse_args([])
985 Namespace()
986 >>> parser.parse_args(['--foo', '1'])
987 Namespace(foo='1')
988
989
990type
991^^^^
992
Éric Araujod9d7bca2011-08-10 04:19:03 +0200993By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300994strings. However, quite often the command-line string should instead be
995interpreted as another type, like a :class:`float` or :class:`int`. The
996``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200997necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300998types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000999
1000 >>> parser = argparse.ArgumentParser()
1001 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +00001002 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001003 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +00001004 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001005
Barry Warsaw1dedd0a2012-09-25 10:37:58 -04001006See the section on the default_ keyword argument for information on when the
1007``type`` argument is applied to default arguments.
1008
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001009To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001010factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
1011``errors=`` arguments of the :func:`open` function. For example,
1012``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001013
1014 >>> parser = argparse.ArgumentParser()
1015 >>> parser.add_argument('bar', type=argparse.FileType('w'))
1016 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +00001017 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001018
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001019``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +02001020the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001021
1022 >>> def perfect_square(string):
1023 ... value = int(string)
1024 ... sqrt = math.sqrt(value)
1025 ... if sqrt != int(sqrt):
1026 ... msg = "%r is not a perfect square" % string
1027 ... raise argparse.ArgumentTypeError(msg)
1028 ... return value
1029 ...
1030 >>> parser = argparse.ArgumentParser(prog='PROG')
1031 >>> parser.add_argument('foo', type=perfect_square)
Martin Panterf5e60482016-04-26 11:41:25 +00001032 >>> parser.parse_args(['9'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001033 Namespace(foo=9)
Martin Panterf5e60482016-04-26 11:41:25 +00001034 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001035 usage: PROG [-h] foo
1036 PROG: error: argument foo: '7' is not a perfect square
1037
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001038The choices_ keyword argument may be more convenient for type checkers that
1039simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001040
1041 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001042 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Martin Panterf5e60482016-04-26 11:41:25 +00001043 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001044 Namespace(foo=7)
Martin Panterf5e60482016-04-26 11:41:25 +00001045 >>> parser.parse_args(['11'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001046 usage: PROG [-h] {5,6,7,8,9}
1047 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1048
1049See the choices_ section for more details.
1050
1051
1052choices
1053^^^^^^^
1054
Éric Araujod9d7bca2011-08-10 04:19:03 +02001055Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001056These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001057argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001058parsed, argument values will be checked, and an error message will be displayed
1059if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001060
Chris Jerdonek174ef672013-01-11 19:26:44 -08001061 >>> parser = argparse.ArgumentParser(prog='game.py')
1062 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1063 >>> parser.parse_args(['rock'])
1064 Namespace(move='rock')
1065 >>> parser.parse_args(['fire'])
1066 usage: game.py [-h] {rock,paper,scissors}
1067 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1068 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001069
Chris Jerdonek174ef672013-01-11 19:26:44 -08001070Note that inclusion in the *choices* container is checked after any type_
1071conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001072container should match the type_ specified::
1073
Chris Jerdonek174ef672013-01-11 19:26:44 -08001074 >>> parser = argparse.ArgumentParser(prog='doors.py')
1075 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1076 >>> print(parser.parse_args(['3']))
1077 Namespace(door=3)
1078 >>> parser.parse_args(['4'])
1079 usage: doors.py [-h] {1,2,3}
1080 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001081
Chris Jerdonek174ef672013-01-11 19:26:44 -08001082Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001083value, so :class:`dict` objects, :class:`set` objects, custom containers,
1084etc. are all supported.
1085
1086
1087required
1088^^^^^^^^
1089
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001090In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001091indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001092To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001093keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001094
1095 >>> parser = argparse.ArgumentParser()
1096 >>> parser.add_argument('--foo', required=True)
1097 >>> parser.parse_args(['--foo', 'BAR'])
1098 Namespace(foo='BAR')
1099 >>> parser.parse_args([])
1100 usage: argparse.py [-h] [--foo FOO]
1101 argparse.py: error: option --foo is required
1102
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001103As the example shows, if an option is marked as ``required``,
1104:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1105present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001106
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001107.. note::
1108
1109 Required options are generally considered bad form because users expect
1110 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001111
1112
1113help
1114^^^^
1115
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001116The ``help`` value is a string containing a brief description of the argument.
1117When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001118command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001119argument::
1120
1121 >>> parser = argparse.ArgumentParser(prog='frobble')
1122 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001123 ... help='foo the bars before frobbling')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001124 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001125 ... help='one of the bars to be frobbled')
Martin Panterf5e60482016-04-26 11:41:25 +00001126 >>> parser.parse_args(['-h'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001127 usage: frobble [-h] [--foo] bar [bar ...]
1128
1129 positional arguments:
1130 bar one of the bars to be frobbled
1131
1132 optional arguments:
1133 -h, --help show this help message and exit
1134 --foo foo the bars before frobbling
1135
1136The ``help`` strings can include various format specifiers to avoid repetition
1137of things like the program name or the argument default_. The available
1138specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001139:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001140
1141 >>> parser = argparse.ArgumentParser(prog='frobble')
1142 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001143 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001144 >>> parser.print_help()
1145 usage: frobble [-h] [bar]
1146
1147 positional arguments:
1148 bar the bar to frobble (default: 42)
1149
1150 optional arguments:
1151 -h, --help show this help message and exit
1152
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001153As the help string supports %-formatting, if you want a literal ``%`` to appear
1154in the help string, you must escape it as ``%%``.
1155
Sandro Tosiea320ab2012-01-03 18:37:03 +01001156:mod:`argparse` supports silencing the help entry for certain options, by
1157setting the ``help`` value to ``argparse.SUPPRESS``::
1158
1159 >>> parser = argparse.ArgumentParser(prog='frobble')
1160 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1161 >>> parser.print_help()
1162 usage: frobble [-h]
1163
1164 optional arguments:
1165 -h, --help show this help message and exit
1166
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001167
1168metavar
1169^^^^^^^
1170
Sandro Tosi32587fb2013-01-11 10:49:00 +01001171When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001172to each expected argument. By default, ArgumentParser objects use the dest_
1173value as the "name" of each object. By default, for positional argument
1174actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001175the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001176``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001177optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001178will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001179
1180 >>> parser = argparse.ArgumentParser()
1181 >>> parser.add_argument('--foo')
1182 >>> parser.add_argument('bar')
1183 >>> parser.parse_args('X --foo Y'.split())
1184 Namespace(bar='X', foo='Y')
1185 >>> parser.print_help()
1186 usage: [-h] [--foo FOO] bar
1187
1188 positional arguments:
1189 bar
1190
1191 optional arguments:
1192 -h, --help show this help message and exit
1193 --foo FOO
1194
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001195An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001196
1197 >>> parser = argparse.ArgumentParser()
1198 >>> parser.add_argument('--foo', metavar='YYY')
1199 >>> parser.add_argument('bar', metavar='XXX')
1200 >>> parser.parse_args('X --foo Y'.split())
1201 Namespace(bar='X', foo='Y')
1202 >>> parser.print_help()
1203 usage: [-h] [--foo YYY] XXX
1204
1205 positional arguments:
1206 XXX
1207
1208 optional arguments:
1209 -h, --help show this help message and exit
1210 --foo YYY
1211
1212Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001213attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1214by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001215
1216Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001217Providing a tuple to ``metavar`` specifies a different display for each of the
1218arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001219
1220 >>> parser = argparse.ArgumentParser(prog='PROG')
1221 >>> parser.add_argument('-x', nargs=2)
1222 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1223 >>> parser.print_help()
1224 usage: PROG [-h] [-x X X] [--foo bar baz]
1225
1226 optional arguments:
1227 -h, --help show this help message and exit
1228 -x X X
1229 --foo bar baz
1230
1231
1232dest
1233^^^^
1234
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001235Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001236object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1237attribute is determined by the ``dest`` keyword argument of
1238:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1239``dest`` is normally supplied as the first argument to
1240:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001241
1242 >>> parser = argparse.ArgumentParser()
1243 >>> parser.add_argument('bar')
Martin Panterf5e60482016-04-26 11:41:25 +00001244 >>> parser.parse_args(['XXX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001245 Namespace(bar='XXX')
1246
1247For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001248the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001249taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001250string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001251the first short option string by stripping the initial ``-`` character. Any
1252internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001253the string is a valid attribute name. The examples below illustrate this
1254behavior::
1255
1256 >>> parser = argparse.ArgumentParser()
1257 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1258 >>> parser.add_argument('-x', '-y')
1259 >>> parser.parse_args('-f 1 -x 2'.split())
1260 Namespace(foo_bar='1', x='2')
1261 >>> parser.parse_args('--foo 1 -y 2'.split())
1262 Namespace(foo_bar='1', x='2')
1263
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001264``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001265
1266 >>> parser = argparse.ArgumentParser()
1267 >>> parser.add_argument('--foo', dest='bar')
1268 >>> parser.parse_args('--foo XXX'.split())
1269 Namespace(bar='XXX')
1270
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001271Action classes
1272^^^^^^^^^^^^^^
1273
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001274Action classes implement the Action API, a callable which returns a callable
1275which processes arguments from the command-line. Any object which follows
1276this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001277:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001278
Terry Jan Reedyee558262014-08-23 22:21:47 -04001279.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1280 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001281 metavar=None)
1282
1283Action objects are used by an ArgumentParser to represent the information
1284needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001285command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001286plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001287except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001288
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001289Instances of Action (or return value of any callable to the ``action``
1290parameter) should have attributes "dest", "option_strings", "default", "type",
1291"required", "help", etc. defined. The easiest way to ensure these attributes
1292are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001293
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001294Action instances should be callable, so subclasses must override the
1295``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001296
1297* ``parser`` - The ArgumentParser object which contains this action.
1298
1299* ``namespace`` - The :class:`Namespace` object that will be returned by
1300 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1301 object using :func:`setattr`.
1302
1303* ``values`` - The associated command-line arguments, with any type conversions
1304 applied. Type conversions are specified with the type_ keyword argument to
1305 :meth:`~ArgumentParser.add_argument`.
1306
1307* ``option_string`` - The option string that was used to invoke this action.
1308 The ``option_string`` argument is optional, and will be absent if the action
1309 is associated with a positional argument.
1310
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001311The ``__call__`` method may perform arbitrary actions, but will typically set
1312attributes on the ``namespace`` based on ``dest`` and ``values``.
1313
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001314
1315The parse_args() method
1316-----------------------
1317
Georg Brandle0bf91d2010-10-17 10:34:28 +00001318.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001319
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001320 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001321 namespace. Return the populated namespace.
1322
1323 Previous calls to :meth:`add_argument` determine exactly what objects are
1324 created and how they are assigned. See the documentation for
1325 :meth:`add_argument` for details.
1326
Éric Araujofde92422011-08-19 01:30:26 +02001327 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001328 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001329
Georg Brandle0bf91d2010-10-17 10:34:28 +00001330
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001331Option value syntax
1332^^^^^^^^^^^^^^^^^^^
1333
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001334The :meth:`~ArgumentParser.parse_args` method supports several ways of
1335specifying the value of an option (if it takes one). In the simplest case, the
1336option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001337
1338 >>> parser = argparse.ArgumentParser(prog='PROG')
1339 >>> parser.add_argument('-x')
1340 >>> parser.add_argument('--foo')
Martin Panterf5e60482016-04-26 11:41:25 +00001341 >>> parser.parse_args(['-x', 'X'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001342 Namespace(foo=None, x='X')
Martin Panterf5e60482016-04-26 11:41:25 +00001343 >>> parser.parse_args(['--foo', 'FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001344 Namespace(foo='FOO', x=None)
1345
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001346For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001347and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001348separate them::
1349
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 short options (options only one character long), the option and its value
1354can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001355
Martin Panterf5e60482016-04-26 11:41:25 +00001356 >>> parser.parse_args(['-xX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001357 Namespace(foo=None, x='X')
1358
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001359Several short options can be joined together, using only a single ``-`` prefix,
1360as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001361
1362 >>> parser = argparse.ArgumentParser(prog='PROG')
1363 >>> parser.add_argument('-x', action='store_true')
1364 >>> parser.add_argument('-y', action='store_true')
1365 >>> parser.add_argument('-z')
Martin Panterf5e60482016-04-26 11:41:25 +00001366 >>> parser.parse_args(['-xyzZ'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001367 Namespace(x=True, y=True, z='Z')
1368
1369
1370Invalid arguments
1371^^^^^^^^^^^^^^^^^
1372
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001373While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1374variety of errors, including ambiguous options, invalid types, invalid options,
1375wrong number of positional arguments, etc. When it encounters such an error,
1376it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001377
1378 >>> parser = argparse.ArgumentParser(prog='PROG')
1379 >>> parser.add_argument('--foo', type=int)
1380 >>> parser.add_argument('bar', nargs='?')
1381
1382 >>> # invalid type
1383 >>> parser.parse_args(['--foo', 'spam'])
1384 usage: PROG [-h] [--foo FOO] [bar]
1385 PROG: error: argument --foo: invalid int value: 'spam'
1386
1387 >>> # invalid option
1388 >>> parser.parse_args(['--bar'])
1389 usage: PROG [-h] [--foo FOO] [bar]
1390 PROG: error: no such option: --bar
1391
1392 >>> # wrong number of arguments
1393 >>> parser.parse_args(['spam', 'badger'])
1394 usage: PROG [-h] [--foo FOO] [bar]
1395 PROG: error: extra arguments found: badger
1396
1397
Éric Araujo543edbd2011-08-19 01:45:12 +02001398Arguments containing ``-``
1399^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001400
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001401The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1402the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001403ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001404attempt to specify an option or an attempt to provide a positional argument.
1405The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001406arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001407there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001408
1409 >>> parser = argparse.ArgumentParser(prog='PROG')
1410 >>> parser.add_argument('-x')
1411 >>> parser.add_argument('foo', nargs='?')
1412
1413 >>> # no negative number options, so -1 is a positional argument
1414 >>> parser.parse_args(['-x', '-1'])
1415 Namespace(foo=None, x='-1')
1416
1417 >>> # no negative number options, so -1 and -5 are positional arguments
1418 >>> parser.parse_args(['-x', '-1', '-5'])
1419 Namespace(foo='-5', x='-1')
1420
1421 >>> parser = argparse.ArgumentParser(prog='PROG')
1422 >>> parser.add_argument('-1', dest='one')
1423 >>> parser.add_argument('foo', nargs='?')
1424
1425 >>> # negative number options present, so -1 is an option
1426 >>> parser.parse_args(['-1', 'X'])
1427 Namespace(foo=None, one='X')
1428
1429 >>> # negative number options present, so -2 is an option
1430 >>> parser.parse_args(['-2'])
1431 usage: PROG [-h] [-1 ONE] [foo]
1432 PROG: error: no such option: -2
1433
1434 >>> # negative number options present, so both -1s are options
1435 >>> parser.parse_args(['-1', '-1'])
1436 usage: PROG [-h] [-1 ONE] [foo]
1437 PROG: error: argument -1: expected one argument
1438
Éric Araujo543edbd2011-08-19 01:45:12 +02001439If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001440like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001441:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1442argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001443
1444 >>> parser.parse_args(['--', '-f'])
1445 Namespace(foo='-f', one=None)
1446
Eli Benderskyf3114532013-12-02 05:49:54 -08001447.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001448
Eli Benderskyf3114532013-12-02 05:49:54 -08001449Argument abbreviations (prefix matching)
1450^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001451
Berker Peksag8089cd62015-02-14 01:39:17 +02001452The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>`
1453allows long options to be abbreviated to a prefix, if the abbreviation is
1454unambiguous (the prefix matches a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001455
1456 >>> parser = argparse.ArgumentParser(prog='PROG')
1457 >>> parser.add_argument('-bacon')
1458 >>> parser.add_argument('-badger')
1459 >>> parser.parse_args('-bac MMM'.split())
1460 Namespace(bacon='MMM', badger=None)
1461 >>> parser.parse_args('-bad WOOD'.split())
1462 Namespace(bacon=None, badger='WOOD')
1463 >>> parser.parse_args('-ba BA'.split())
1464 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1465 PROG: error: ambiguous option: -ba could match -badger, -bacon
1466
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001467An error is produced for arguments that could produce more than one options.
Berker Peksag8089cd62015-02-14 01:39:17 +02001468This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001469
1470
1471Beyond ``sys.argv``
1472^^^^^^^^^^^^^^^^^^^
1473
Éric Araujod9d7bca2011-08-10 04:19:03 +02001474Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001475of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001476:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1477interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001478
1479 >>> parser = argparse.ArgumentParser()
1480 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001481 ... 'integers', metavar='int', type=int, choices=range(10),
Serhiy Storchakadba90392016-05-10 12:01:23 +03001482 ... nargs='+', help='an integer in the range 0..9')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001483 >>> parser.add_argument(
1484 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001485 ... default=max, help='sum the integers (default: find the max)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001486 >>> parser.parse_args(['1', '2', '3', '4'])
1487 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panterf5e60482016-04-26 11:41:25 +00001488 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001489 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1490
1491
Steven Bethardd8f2d502011-03-26 19:50:06 +01001492The Namespace object
1493^^^^^^^^^^^^^^^^^^^^
1494
Éric Araujo63b18a42011-07-29 17:59:17 +02001495.. class:: Namespace
1496
1497 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1498 an object holding attributes and return it.
1499
1500This class is deliberately simple, just an :class:`object` subclass with a
1501readable string representation. If you prefer to have dict-like view of the
1502attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001503
1504 >>> parser = argparse.ArgumentParser()
1505 >>> parser.add_argument('--foo')
1506 >>> args = parser.parse_args(['--foo', 'BAR'])
1507 >>> vars(args)
1508 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001509
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001510It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001511already existing object, rather than a new :class:`Namespace` object. This can
1512be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001513
Éric Araujo28053fb2010-11-22 03:09:19 +00001514 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001515 ... pass
1516 ...
1517 >>> c = C()
1518 >>> parser = argparse.ArgumentParser()
1519 >>> parser.add_argument('--foo')
1520 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1521 >>> c.foo
1522 'BAR'
1523
1524
1525Other utilities
1526---------------
1527
1528Sub-commands
1529^^^^^^^^^^^^
1530
Georg Brandlfc9a1132013-10-06 18:51:39 +02001531.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1532 [parser_class], [action], \
1533 [option_string], [dest], [help], \
1534 [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001535
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001536 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001537 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001538 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001539 this way can be a particularly good idea when a program performs several
1540 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001541 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001542 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001543 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001544 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1545 command name and any :class:`ArgumentParser` constructor arguments, and
1546 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001547
Georg Brandlfc9a1132013-10-06 18:51:39 +02001548 Description of parameters:
1549
1550 * title - title for the sub-parser group in help output; by default
1551 "subcommands" if description is provided, otherwise uses title for
1552 positional arguments
1553
1554 * description - description for the sub-parser group in help output, by
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001555 default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001556
1557 * prog - usage information that will be displayed with sub-command help,
1558 by default the name of the program and any positional arguments before the
1559 subparser argument
1560
1561 * parser_class - class which will be used to create sub-parser instances, by
1562 default the class of the current parser (e.g. ArgumentParser)
1563
Berker Peksag5a494f62015-01-20 06:45:53 +02001564 * action_ - the basic type of action to be taken when this argument is
1565 encountered at the command line
1566
1567 * dest_ - name of the attribute under which sub-command name will be
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001568 stored; by default ``None`` and no value is stored
Georg Brandlfc9a1132013-10-06 18:51:39 +02001569
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001570 * help_ - help for sub-parser group in help output, by default ``None``
Georg Brandlfc9a1132013-10-06 18:51:39 +02001571
Berker Peksag5a494f62015-01-20 06:45:53 +02001572 * metavar_ - string presenting available sub-commands in help; by default it
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001573 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
Georg Brandlfc9a1132013-10-06 18:51:39 +02001574
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001575 Some example usage::
1576
1577 >>> # create the top-level parser
1578 >>> parser = argparse.ArgumentParser(prog='PROG')
1579 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1580 >>> subparsers = parser.add_subparsers(help='sub-command help')
1581 >>>
1582 >>> # create the parser for the "a" command
1583 >>> parser_a = subparsers.add_parser('a', help='a help')
1584 >>> parser_a.add_argument('bar', type=int, help='bar help')
1585 >>>
1586 >>> # create the parser for the "b" command
1587 >>> parser_b = subparsers.add_parser('b', help='b help')
1588 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1589 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001590 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001591 >>> parser.parse_args(['a', '12'])
1592 Namespace(bar=12, foo=False)
1593 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1594 Namespace(baz='Z', foo=True)
1595
1596 Note that the object returned by :meth:`parse_args` will only contain
1597 attributes for the main parser and the subparser that was selected by the
1598 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001599 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1600 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001601 ``baz`` attributes are present.
1602
1603 Similarly, when a help message is requested from a subparser, only the help
1604 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001605 include parent parser or sibling parser messages. (A help message for each
1606 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001607 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001608
1609 ::
1610
1611 >>> parser.parse_args(['--help'])
1612 usage: PROG [-h] [--foo] {a,b} ...
1613
1614 positional arguments:
1615 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001616 a a help
1617 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001618
1619 optional arguments:
1620 -h, --help show this help message and exit
1621 --foo foo help
1622
1623 >>> parser.parse_args(['a', '--help'])
1624 usage: PROG a [-h] bar
1625
1626 positional arguments:
1627 bar bar help
1628
1629 optional arguments:
1630 -h, --help show this help message and exit
1631
1632 >>> parser.parse_args(['b', '--help'])
1633 usage: PROG b [-h] [--baz {X,Y,Z}]
1634
1635 optional arguments:
1636 -h, --help show this help message and exit
1637 --baz {X,Y,Z} baz help
1638
1639 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1640 keyword arguments. When either is present, the subparser's commands will
1641 appear in their own group in the help output. For example::
1642
1643 >>> parser = argparse.ArgumentParser()
1644 >>> subparsers = parser.add_subparsers(title='subcommands',
1645 ... description='valid subcommands',
1646 ... help='additional help')
1647 >>> subparsers.add_parser('foo')
1648 >>> subparsers.add_parser('bar')
1649 >>> parser.parse_args(['-h'])
1650 usage: [-h] {foo,bar} ...
1651
1652 optional arguments:
1653 -h, --help show this help message and exit
1654
1655 subcommands:
1656 valid subcommands
1657
1658 {foo,bar} additional help
1659
Steven Bethardfd311a72010-12-18 11:19:23 +00001660 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1661 which allows multiple strings to refer to the same subparser. This example,
1662 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1663
1664 >>> parser = argparse.ArgumentParser()
1665 >>> subparsers = parser.add_subparsers()
1666 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1667 >>> checkout.add_argument('foo')
1668 >>> parser.parse_args(['co', 'bar'])
1669 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001670
1671 One particularly effective way of handling sub-commands is to combine the use
1672 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1673 that each subparser knows which Python function it should execute. For
1674 example::
1675
1676 >>> # sub-command functions
1677 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001678 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001679 ...
1680 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001681 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001682 ...
1683 >>> # create the top-level parser
1684 >>> parser = argparse.ArgumentParser()
1685 >>> subparsers = parser.add_subparsers()
1686 >>>
1687 >>> # create the parser for the "foo" command
1688 >>> parser_foo = subparsers.add_parser('foo')
1689 >>> parser_foo.add_argument('-x', type=int, default=1)
1690 >>> parser_foo.add_argument('y', type=float)
1691 >>> parser_foo.set_defaults(func=foo)
1692 >>>
1693 >>> # create the parser for the "bar" command
1694 >>> parser_bar = subparsers.add_parser('bar')
1695 >>> parser_bar.add_argument('z')
1696 >>> parser_bar.set_defaults(func=bar)
1697 >>>
1698 >>> # parse the args and call whatever function was selected
1699 >>> args = parser.parse_args('foo 1 -x 2'.split())
1700 >>> args.func(args)
1701 2.0
1702 >>>
1703 >>> # parse the args and call whatever function was selected
1704 >>> args = parser.parse_args('bar XYZYX'.split())
1705 >>> args.func(args)
1706 ((XYZYX))
1707
Steven Bethardfd311a72010-12-18 11:19:23 +00001708 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001709 appropriate function after argument parsing is complete. Associating
1710 functions with actions like this is typically the easiest way to handle the
1711 different actions for each of your subparsers. However, if it is necessary
1712 to check the name of the subparser that was invoked, the ``dest`` keyword
1713 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001714
1715 >>> parser = argparse.ArgumentParser()
1716 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1717 >>> subparser1 = subparsers.add_parser('1')
1718 >>> subparser1.add_argument('-x')
1719 >>> subparser2 = subparsers.add_parser('2')
1720 >>> subparser2.add_argument('y')
1721 >>> parser.parse_args(['2', 'frobble'])
1722 Namespace(subparser_name='2', y='frobble')
1723
1724
1725FileType objects
1726^^^^^^^^^^^^^^^^
1727
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001728.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001729
1730 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001731 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001732 :class:`FileType` objects as their type will open command-line arguments as
1733 files with the requested modes, buffer sizes, encodings and error handling
1734 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001735
Éric Araujoc3ef0372012-02-20 01:44:55 +01001736 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001737 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1738 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1739 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1740 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 +00001741
1742 FileType objects understand the pseudo-argument ``'-'`` and automatically
1743 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001744 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001745
Éric Araujoc3ef0372012-02-20 01:44:55 +01001746 >>> parser = argparse.ArgumentParser()
1747 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1748 >>> parser.parse_args(['-'])
1749 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001750
R David Murrayfced3ec2013-12-31 11:18:01 -05001751 .. versionadded:: 3.4
1752 The *encodings* and *errors* keyword arguments.
1753
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001754
1755Argument groups
1756^^^^^^^^^^^^^^^
1757
Georg Brandle0bf91d2010-10-17 10:34:28 +00001758.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001759
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001760 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001761 "positional arguments" and "optional arguments" when displaying help
1762 messages. When there is a better conceptual grouping of arguments than this
1763 default one, appropriate groups can be created using the
1764 :meth:`add_argument_group` method::
1765
1766 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1767 >>> group = parser.add_argument_group('group')
1768 >>> group.add_argument('--foo', help='foo help')
1769 >>> group.add_argument('bar', help='bar help')
1770 >>> parser.print_help()
1771 usage: PROG [--foo FOO] bar
1772
1773 group:
1774 bar bar help
1775 --foo FOO foo help
1776
1777 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001778 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1779 :class:`ArgumentParser`. When an argument is added to the group, the parser
1780 treats it just like a normal argument, but displays the argument in a
1781 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001782 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001783 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001784
1785 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1786 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1787 >>> group1.add_argument('foo', help='foo help')
1788 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1789 >>> group2.add_argument('--bar', help='bar help')
1790 >>> parser.print_help()
1791 usage: PROG [--bar BAR] foo
1792
1793 group1:
1794 group1 description
1795
1796 foo foo help
1797
1798 group2:
1799 group2 description
1800
1801 --bar BAR bar help
1802
Sandro Tosi99e7d072012-03-26 19:36:23 +02001803 Note that any arguments not in your user-defined groups will end up back
1804 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001805
1806
1807Mutual exclusion
1808^^^^^^^^^^^^^^^^
1809
Georg Brandled86ff82013-10-06 13:09:59 +02001810.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001811
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001812 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1813 one of the arguments in the mutually exclusive group was present on the
1814 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001815
1816 >>> parser = argparse.ArgumentParser(prog='PROG')
1817 >>> group = parser.add_mutually_exclusive_group()
1818 >>> group.add_argument('--foo', action='store_true')
1819 >>> group.add_argument('--bar', action='store_false')
1820 >>> parser.parse_args(['--foo'])
1821 Namespace(bar=True, foo=True)
1822 >>> parser.parse_args(['--bar'])
1823 Namespace(bar=False, foo=False)
1824 >>> parser.parse_args(['--foo', '--bar'])
1825 usage: PROG [-h] [--foo | --bar]
1826 PROG: error: argument --bar: not allowed with argument --foo
1827
Georg Brandle0bf91d2010-10-17 10:34:28 +00001828 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001829 argument, to indicate that at least one of the mutually exclusive arguments
1830 is required::
1831
1832 >>> parser = argparse.ArgumentParser(prog='PROG')
1833 >>> group = parser.add_mutually_exclusive_group(required=True)
1834 >>> group.add_argument('--foo', action='store_true')
1835 >>> group.add_argument('--bar', action='store_false')
1836 >>> parser.parse_args([])
1837 usage: PROG [-h] (--foo | --bar)
1838 PROG: error: one of the arguments --foo --bar is required
1839
1840 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001841 *title* and *description* arguments of
1842 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001843
1844
1845Parser defaults
1846^^^^^^^^^^^^^^^
1847
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001848.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001849
1850 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001851 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001852 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001853 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001854 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001855
1856 >>> parser = argparse.ArgumentParser()
1857 >>> parser.add_argument('foo', type=int)
1858 >>> parser.set_defaults(bar=42, baz='badger')
1859 >>> parser.parse_args(['736'])
1860 Namespace(bar=42, baz='badger', foo=736)
1861
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001862 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001863
1864 >>> parser = argparse.ArgumentParser()
1865 >>> parser.add_argument('--foo', default='bar')
1866 >>> parser.set_defaults(foo='spam')
1867 >>> parser.parse_args([])
1868 Namespace(foo='spam')
1869
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001870 Parser-level defaults can be particularly useful when working with multiple
1871 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1872 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001873
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001874.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001875
1876 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001877 :meth:`~ArgumentParser.add_argument` or by
1878 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001879
1880 >>> parser = argparse.ArgumentParser()
1881 >>> parser.add_argument('--foo', default='badger')
1882 >>> parser.get_default('foo')
1883 'badger'
1884
1885
1886Printing help
1887^^^^^^^^^^^^^
1888
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001889In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1890care of formatting and printing any usage or error messages. However, several
1891formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001892
Georg Brandle0bf91d2010-10-17 10:34:28 +00001893.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001894
1895 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001896 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001897 assumed.
1898
Georg Brandle0bf91d2010-10-17 10:34:28 +00001899.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001900
1901 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001902 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001903 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001904
1905There are also variants of these methods that simply return a string instead of
1906printing it:
1907
Georg Brandle0bf91d2010-10-17 10:34:28 +00001908.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001909
1910 Return a string containing a brief description of how the
1911 :class:`ArgumentParser` should be invoked on the command line.
1912
Georg Brandle0bf91d2010-10-17 10:34:28 +00001913.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001914
1915 Return a string containing a help message, including the program usage and
1916 information about the arguments registered with the :class:`ArgumentParser`.
1917
1918
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001919Partial parsing
1920^^^^^^^^^^^^^^^
1921
Georg Brandle0bf91d2010-10-17 10:34:28 +00001922.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001923
Georg Brandl69518bc2011-04-16 16:44:54 +02001924Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001925the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001926:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001927:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1928extra arguments are present. Instead, it returns a two item tuple containing
1929the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001930
1931::
1932
1933 >>> parser = argparse.ArgumentParser()
1934 >>> parser.add_argument('--foo', action='store_true')
1935 >>> parser.add_argument('bar')
1936 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1937 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1938
Eli Benderskyf3114532013-12-02 05:49:54 -08001939.. warning::
1940 :ref:`Prefix matching <prefix-matching>` rules apply to
1941 :meth:`parse_known_args`. The parser may consume an option even if it's just
1942 a prefix of one of its known options, instead of leaving it in the remaining
1943 arguments list.
1944
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001945
1946Customizing file parsing
1947^^^^^^^^^^^^^^^^^^^^^^^^
1948
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001949.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001950
Georg Brandle0bf91d2010-10-17 10:34:28 +00001951 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001952 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft8b852f12014-05-20 12:58:38 -04001953 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001954 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001955
Georg Brandle0bf91d2010-10-17 10:34:28 +00001956 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001957 the argument file. It returns a list of arguments parsed from this string.
1958 The method is called once per line read from the argument file, in order.
1959
1960 A useful override of this method is one that treats each space-separated word
Berker Peksag5493e472016-10-17 06:14:17 +03001961 as an argument. The following example demonstrates how to do this::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001962
Berker Peksag5493e472016-10-17 06:14:17 +03001963 class MyArgumentParser(argparse.ArgumentParser):
1964 def convert_arg_line_to_args(self, arg_line):
1965 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001966
1967
Georg Brandl93754922010-10-17 10:28:04 +00001968Exiting methods
1969^^^^^^^^^^^^^^^
1970
1971.. method:: ArgumentParser.exit(status=0, message=None)
1972
1973 This method terminates the program, exiting with the specified *status*
1974 and, if given, it prints a *message* before that.
1975
1976.. method:: ArgumentParser.error(message)
1977
1978 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001979 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001980
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001981.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001982
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001983Upgrading optparse code
1984-----------------------
1985
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001986Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001987with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1988transparently, particularly with the changes required to support the new
1989``nargs=`` specifiers and better usage messages. When most everything in
1990:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1991longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001992
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03001993The :mod:`argparse` module improves on the standard library :mod:`optparse`
1994module in a number of ways including:
1995
1996* Handling positional arguments.
1997* Supporting sub-commands.
1998* Allowing alternative option prefixes like ``+`` and ``/``.
1999* Handling zero-or-more and one-or-more style arguments.
2000* Producing more informative usage messages.
2001* Providing a much simpler interface for custom ``type`` and ``action``.
2002
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03002003A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002004
Ezio Melotti5569e9b2011-04-22 01:42:10 +03002005* Replace all :meth:`optparse.OptionParser.add_option` calls with
2006 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002007
R David Murray5e0c5712012-03-30 18:07:42 -04002008* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00002009 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04002010 calls for the positional arguments. Keep in mind that what was previously
2011 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002012
2013* Replace callback actions and the ``callback_*`` keyword arguments with
2014 ``type`` or ``action`` arguments.
2015
2016* Replace string names for ``type`` keyword arguments with the corresponding
2017 type objects (e.g. int, float, complex, etc).
2018
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002019* Replace :class:`optparse.Values` with :class:`Namespace` and
2020 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
2021 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002022
2023* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03002024 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002025 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00002026
2027* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panterd21e0b52015-10-10 10:36:22 +00002028 ``parser.add_argument('--version', action='version', version='<the version>')``.