blob: 10789e9f883089f3b093c4b951325044f3780bbc [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
48be run at the command line and provides useful help messages::
49
Georg Brandl29fc4bf2013-10-06 19:33:56 +020050 $ python prog.py -h
Benjamin Peterson698a18a2010-03-02 22:34:37 +000051 usage: prog.py [-h] [--sum] N [N ...]
52
53 Process some integers.
54
55 positional arguments:
56 N an integer for the accumulator
57
58 optional arguments:
59 -h, --help show this help message and exit
60 --sum sum the integers (default: find the max)
61
62When run with the appropriate arguments, it prints either the sum or the max of
63the command-line integers::
64
Georg Brandl29fc4bf2013-10-06 19:33:56 +020065 $ python prog.py 1 2 3 4
Benjamin Peterson698a18a2010-03-02 22:34:37 +000066 4
67
Georg Brandl29fc4bf2013-10-06 19:33:56 +020068 $ python prog.py 1 2 3 4 --sum
Benjamin Peterson698a18a2010-03-02 22:34:37 +000069 10
70
71If invalid arguments are passed in, it will issue an error::
72
Georg Brandl29fc4bf2013-10-06 19:33:56 +020073 $ python prog.py a b c
Benjamin Peterson698a18a2010-03-02 22:34:37 +000074 usage: prog.py [-h] [--sum] N [N ...]
75 prog.py: error: argument N: invalid int value: 'a'
76
77The following sections walk you through this example.
78
Georg Brandle0bf91d2010-10-17 10:34:28 +000079
Benjamin Peterson698a18a2010-03-02 22:34:37 +000080Creating a parser
81^^^^^^^^^^^^^^^^^
82
Benjamin Peterson2614cda2010-03-21 22:36:19 +000083The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000084:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000085
86 >>> parser = argparse.ArgumentParser(description='Process some integers.')
87
88The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotticca4ef82011-04-21 15:26:46 +030089parse the command line into Python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000090
91
92Adding arguments
93^^^^^^^^^^^^^^^^
94
Benjamin Peterson98047eb2010-03-03 02:07:08 +000095Filling an :class:`ArgumentParser` with information about program arguments is
96done by making calls to the :meth:`~ArgumentParser.add_argument` method.
97Generally, these calls tell the :class:`ArgumentParser` how to take the strings
98on the command line and turn them into objects. This information is stored and
99used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000100
101 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
102 ... help='an integer for the accumulator')
103 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
104 ... const=sum, default=max,
105 ... help='sum the integers (default: find the max)')
106
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300107Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000108two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
109will be a list of one or more ints, and the ``accumulate`` attribute will be
110either the :func:`sum` function, if ``--sum`` was specified at the command line,
111or the :func:`max` function if it was not.
112
Georg Brandle0bf91d2010-10-17 10:34:28 +0000113
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000114Parsing arguments
115^^^^^^^^^^^^^^^^^
116
Éric Araujod9d7bca2011-08-10 04:19:03 +0200117:class:`ArgumentParser` parses arguments through the
Georg Brandl69518bc2011-04-16 16:44:54 +0200118:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujofde92422011-08-19 01:30:26 +0200119convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujo63b18a42011-07-29 17:59:17 +0200120In most cases, this means a simple :class:`Namespace` object will be built up from
Georg Brandl69518bc2011-04-16 16:44:54 +0200121attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000122
123 >>> parser.parse_args(['--sum', '7', '-1', '42'])
124 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
125
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000126In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
127arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujod9d7bca2011-08-10 04:19:03 +0200128command-line arguments from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000129
130
131ArgumentParser objects
132----------------------
133
Ezio Melottie0add762012-09-14 06:32:35 +0300134.. class:: ArgumentParser(prog=None, usage=None, description=None, \
135 epilog=None, parents=[], \
136 formatter_class=argparse.HelpFormatter, \
137 prefix_chars='-', fromfile_prefix_chars=None, \
138 argument_default=None, conflict_handler='error', \
Berker Peksag8089cd62015-02-14 01:39:17 +0200139 add_help=True, allow_abbrev=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000140
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300141 Create a new :class:`ArgumentParser` object. All parameters should be passed
142 as keyword arguments. Each parameter has its own more detailed description
143 below, but in short they are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000144
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300145 * prog_ - The name of the program (default: ``sys.argv[0]``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000146
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300147 * usage_ - The string describing the program usage (default: generated from
148 arguments added to parser)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000149
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300150 * description_ - Text to display before the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000151
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300152 * epilog_ - Text to display after the argument help (default: none)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000153
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000154 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300155 also be included
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000156
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300157 * formatter_class_ - A class for customizing the help output
158
159 * prefix_chars_ - The set of characters that prefix optional arguments
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000160 (default: '-')
161
162 * fromfile_prefix_chars_ - The set of characters that prefix files from
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300163 which additional arguments should be read (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000164
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300165 * argument_default_ - The global default value for arguments
166 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000167
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300168 * conflict_handler_ - The strategy for resolving conflicting optionals
169 (usually unnecessary)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000170
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300171 * add_help_ - Add a -h/--help option to the parser (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000172
Berker Peksag8089cd62015-02-14 01:39:17 +0200173 * allow_abbrev_ - Allows long options to be abbreviated if the
174 abbreviation is unambiguous. (default: ``True``)
175
176 .. versionchanged:: 3.5
177 *allow_abbrev* parameter was added.
178
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000179The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000180
181
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300182prog
183^^^^
184
185By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
186how to display the name of the program in help messages. This default is almost
187always desirable because it will make the help messages match how the program was
188invoked on the command line. For example, consider a file named
189``myprogram.py`` with the following code::
190
191 import argparse
192 parser = argparse.ArgumentParser()
193 parser.add_argument('--foo', help='foo help')
194 args = parser.parse_args()
195
196The help for this program will display ``myprogram.py`` as the program name
197(regardless of where the program was invoked from)::
198
199 $ python myprogram.py --help
200 usage: myprogram.py [-h] [--foo FOO]
201
202 optional arguments:
203 -h, --help show this help message and exit
204 --foo FOO foo help
205 $ cd ..
206 $ python subdir\myprogram.py --help
207 usage: myprogram.py [-h] [--foo FOO]
208
209 optional arguments:
210 -h, --help show this help message and exit
211 --foo FOO foo help
212
213To change this default behavior, another value can be supplied using the
214``prog=`` argument to :class:`ArgumentParser`::
215
216 >>> parser = argparse.ArgumentParser(prog='myprogram')
217 >>> parser.print_help()
218 usage: myprogram [-h]
219
220 optional arguments:
221 -h, --help show this help message and exit
222
223Note that the program name, whether determined from ``sys.argv[0]`` or from the
224``prog=`` argument, is available to help messages using the ``%(prog)s`` format
225specifier.
226
227::
228
229 >>> parser = argparse.ArgumentParser(prog='myprogram')
230 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
231 >>> parser.print_help()
232 usage: myprogram [-h] [--foo FOO]
233
234 optional arguments:
235 -h, --help show this help message and exit
236 --foo FOO foo of the myprogram program
237
238
239usage
240^^^^^
241
242By default, :class:`ArgumentParser` calculates the usage message from the
243arguments it contains::
244
245 >>> parser = argparse.ArgumentParser(prog='PROG')
246 >>> parser.add_argument('--foo', nargs='?', help='foo help')
247 >>> parser.add_argument('bar', nargs='+', help='bar help')
248 >>> parser.print_help()
249 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
250
251 positional arguments:
252 bar bar help
253
254 optional arguments:
255 -h, --help show this help message and exit
256 --foo [FOO] foo help
257
258The default message can be overridden with the ``usage=`` keyword argument::
259
260 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
261 >>> parser.add_argument('--foo', nargs='?', help='foo help')
262 >>> parser.add_argument('bar', nargs='+', help='bar help')
263 >>> parser.print_help()
264 usage: PROG [options]
265
266 positional arguments:
267 bar bar help
268
269 optional arguments:
270 -h, --help show this help message and exit
271 --foo [FOO] foo help
272
273The ``%(prog)s`` format specifier is available to fill in the program name in
274your usage messages.
275
276
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000277description
278^^^^^^^^^^^
279
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000280Most calls to the :class:`ArgumentParser` constructor will use the
281``description=`` keyword argument. This argument gives a brief description of
282what the program does and how it works. In help messages, the description is
283displayed between the command-line usage string and the help messages for the
284various arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000285
286 >>> parser = argparse.ArgumentParser(description='A foo that bars')
287 >>> parser.print_help()
288 usage: argparse.py [-h]
289
290 A foo that bars
291
292 optional arguments:
293 -h, --help show this help message and exit
294
295By default, the description will be line-wrapped so that it fits within the
296given space. To change this behavior, see the formatter_class_ argument.
297
298
299epilog
300^^^^^^
301
302Some programs like to display additional description of the program after the
303description of the arguments. Such text can be specified using the ``epilog=``
304argument to :class:`ArgumentParser`::
305
306 >>> parser = argparse.ArgumentParser(
307 ... description='A foo that bars',
308 ... epilog="And that's how you'd foo a bar")
309 >>> parser.print_help()
310 usage: argparse.py [-h]
311
312 A foo that bars
313
314 optional arguments:
315 -h, --help show this help message and exit
316
317 And that's how you'd foo a bar
318
319As with the description_ argument, the ``epilog=`` text is by default
320line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000321argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000322
323
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000324parents
325^^^^^^^
326
327Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000328repeating the definitions of these arguments, a single parser with all the
329shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
330can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
331objects, collects all the positional and optional actions from them, and adds
332these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000333
334 >>> parent_parser = argparse.ArgumentParser(add_help=False)
335 >>> parent_parser.add_argument('--parent', type=int)
336
337 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
338 >>> foo_parser.add_argument('foo')
339 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
340 Namespace(foo='XXX', parent=2)
341
342 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
343 >>> bar_parser.add_argument('--bar')
344 >>> bar_parser.parse_args(['--bar', 'YYY'])
345 Namespace(bar='YYY', parent=None)
346
347Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000348:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
349and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000350
Steven Bethardd186f992011-03-26 21:49:00 +0100351.. note::
352 You must fully initialize the parsers before passing them via ``parents=``.
353 If you change the parent parsers after the child parser, those changes will
354 not be reflected in the child.
355
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000356
357formatter_class
358^^^^^^^^^^^^^^^
359
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000360:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300361specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300362classes:
363
364.. class:: RawDescriptionHelpFormatter
365 RawTextHelpFormatter
366 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300367 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000368
Steven Bethard0331e902011-03-26 14:48:04 +0100369:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
370more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000371By default, :class:`ArgumentParser` objects line-wrap the description_ and
372epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000373
374 >>> parser = argparse.ArgumentParser(
375 ... prog='PROG',
376 ... description='''this description
377 ... was indented weird
378 ... but that is okay''',
379 ... epilog='''
380 ... likewise for this epilog whose whitespace will
381 ... be cleaned up and whose words will be wrapped
382 ... across a couple lines''')
383 >>> parser.print_help()
384 usage: PROG [-h]
385
386 this description was indented weird but that is okay
387
388 optional arguments:
389 -h, --help show this help message and exit
390
391 likewise for this epilog whose whitespace will be cleaned up and whose words
392 will be wrapped across a couple lines
393
Steven Bethard0331e902011-03-26 14:48:04 +0100394Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000395indicates that description_ and epilog_ are already correctly formatted and
396should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000397
398 >>> parser = argparse.ArgumentParser(
399 ... prog='PROG',
400 ... formatter_class=argparse.RawDescriptionHelpFormatter,
401 ... description=textwrap.dedent('''\
402 ... Please do not mess up this text!
403 ... --------------------------------
404 ... I have indented it
405 ... exactly the way
406 ... I want it
407 ... '''))
408 >>> parser.print_help()
409 usage: PROG [-h]
410
411 Please do not mess up this text!
412 --------------------------------
413 I have indented it
414 exactly the way
415 I want it
416
417 optional arguments:
418 -h, --help show this help message and exit
419
Steven Bethard0331e902011-03-26 14:48:04 +0100420:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000421including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000422
Steven Bethard0331e902011-03-26 14:48:04 +0100423:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
424default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000425
426 >>> parser = argparse.ArgumentParser(
427 ... prog='PROG',
428 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
429 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
430 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
431 >>> parser.print_help()
432 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
433
434 positional arguments:
435 bar BAR! (default: [1, 2, 3])
436
437 optional arguments:
438 -h, --help show this help message and exit
439 --foo FOO FOO! (default: 42)
440
Steven Bethard0331e902011-03-26 14:48:04 +0100441:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300442argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100443as the regular formatter does)::
444
445 >>> parser = argparse.ArgumentParser(
446 ... prog='PROG',
447 ... formatter_class=argparse.MetavarTypeHelpFormatter)
448 >>> parser.add_argument('--foo', type=int)
449 >>> parser.add_argument('bar', type=float)
450 >>> parser.print_help()
451 usage: PROG [-h] [--foo int] float
452
453 positional arguments:
454 float
455
456 optional arguments:
457 -h, --help show this help message and exit
458 --foo int
459
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000460
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300461prefix_chars
462^^^^^^^^^^^^
463
464Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
465Parsers that need to support different or additional prefix
466characters, e.g. for options
467like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
468to the ArgumentParser constructor::
469
470 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
471 >>> parser.add_argument('+f')
472 >>> parser.add_argument('++bar')
473 >>> parser.parse_args('+f X ++bar Y'.split())
474 Namespace(bar='Y', f='X')
475
476The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
477characters that does not include ``-`` will cause ``-f/--foo`` options to be
478disallowed.
479
480
481fromfile_prefix_chars
482^^^^^^^^^^^^^^^^^^^^^
483
484Sometimes, for example when dealing with a particularly long argument lists, it
485may make sense to keep the list of arguments in a file rather than typing it out
486at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
487:class:`ArgumentParser` constructor, then arguments that start with any of the
488specified characters will be treated as files, and will be replaced by the
489arguments they contain. For example::
490
491 >>> with open('args.txt', 'w') as fp:
Serhiy Storchakadba90392016-05-10 12:01:23 +0300492 ... fp.write('-f\nbar')
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300493 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
494 >>> parser.add_argument('-f')
495 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
496 Namespace(f='bar')
497
498Arguments read from a file must by default be one per line (but see also
499:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
500were in the same place as the original file referencing argument on the command
501line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
502is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
503
504The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
505arguments will never be treated as file references.
506
507
508argument_default
509^^^^^^^^^^^^^^^^
510
511Generally, argument defaults are specified either by passing a default to
512:meth:`~ArgumentParser.add_argument` or by calling the
513:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
514pairs. Sometimes however, it may be useful to specify a single parser-wide
515default for arguments. This can be accomplished by passing the
516``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
517to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
518calls, we supply ``argument_default=SUPPRESS``::
519
520 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
521 >>> parser.add_argument('--foo')
522 >>> parser.add_argument('bar', nargs='?')
523 >>> parser.parse_args(['--foo', '1', 'BAR'])
524 Namespace(bar='BAR', foo='1')
525 >>> parser.parse_args([])
526 Namespace()
527
Berker Peksag8089cd62015-02-14 01:39:17 +0200528.. _allow_abbrev:
529
530allow_abbrev
531^^^^^^^^^^^^
532
533Normally, when you pass an argument list to the
Martin Panterd2ad5712015-11-02 04:20:33 +0000534:meth:`~ArgumentParser.parse_args` method of an :class:`ArgumentParser`,
Berker Peksag8089cd62015-02-14 01:39:17 +0200535it :ref:`recognizes abbreviations <prefix-matching>` of long options.
536
537This feature can be disabled by setting ``allow_abbrev`` to ``False``::
538
539 >>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
540 >>> parser.add_argument('--foobar', action='store_true')
541 >>> parser.add_argument('--foonley', action='store_false')
Berker Peksage7e497b2015-03-12 20:47:41 +0200542 >>> parser.parse_args(['--foon'])
Berker Peksag8089cd62015-02-14 01:39:17 +0200543 usage: PROG [-h] [--foobar] [--foonley]
544 PROG: error: unrecognized arguments: --foon
545
546.. versionadded:: 3.5
547
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300548
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000549conflict_handler
550^^^^^^^^^^^^^^^^
551
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000552:class:`ArgumentParser` objects do not allow two actions with the same option
553string. By default, :class:`ArgumentParser` objects raises an exception if an
554attempt is made to create an argument with an option string that is already in
555use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000556
557 >>> parser = argparse.ArgumentParser(prog='PROG')
558 >>> parser.add_argument('-f', '--foo', help='old foo help')
559 >>> parser.add_argument('--foo', help='new foo help')
560 Traceback (most recent call last):
561 ..
562 ArgumentError: argument --foo: conflicting option string(s): --foo
563
564Sometimes (e.g. when using parents_) it may be useful to simply override any
565older arguments with the same option string. To get this behavior, the value
566``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000567:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000568
569 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
570 >>> parser.add_argument('-f', '--foo', help='old foo help')
571 >>> parser.add_argument('--foo', help='new foo help')
572 >>> parser.print_help()
573 usage: PROG [-h] [-f FOO] [--foo FOO]
574
575 optional arguments:
576 -h, --help show this help message and exit
577 -f FOO old foo help
578 --foo FOO new foo help
579
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000580Note that :class:`ArgumentParser` objects only remove an action if all of its
581option strings are overridden. So, in the example above, the old ``-f/--foo``
582action is retained as the ``-f`` action, because only the ``--foo`` option
583string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000584
585
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300586add_help
587^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000588
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300589By default, ArgumentParser objects add an option which simply displays
590the parser's help message. For example, consider a file named
591``myprogram.py`` containing the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000592
593 import argparse
594 parser = argparse.ArgumentParser()
595 parser.add_argument('--foo', help='foo help')
596 args = parser.parse_args()
597
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300598If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
599help will be printed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000600
601 $ python myprogram.py --help
602 usage: myprogram.py [-h] [--foo FOO]
603
604 optional arguments:
605 -h, --help show this help message and exit
606 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000607
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300608Occasionally, it may be useful to disable the addition of this help option.
609This can be achieved by passing ``False`` as the ``add_help=`` argument to
610:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000611
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300612 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
613 >>> parser.add_argument('--foo', help='foo help')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000614 >>> parser.print_help()
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300615 usage: PROG [--foo FOO]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000616
617 optional arguments:
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300618 --foo FOO foo help
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000619
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300620The help option is typically ``-h/--help``. The exception to this is
621if the ``prefix_chars=`` is specified and does not include ``-``, in
622which case ``-h`` and ``--help`` are not valid options. In
623this case, the first character in ``prefix_chars`` is used to prefix
624the help options::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000625
Andrew Svetlov5b6e1ca2013-04-07 14:43:17 +0300626 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000627 >>> parser.print_help()
Georg Brandld2914ce2013-10-06 09:50:36 +0200628 usage: PROG [+h]
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000629
630 optional arguments:
Georg Brandld2914ce2013-10-06 09:50:36 +0200631 +h, ++help show this help message and exit
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000632
633
634The add_argument() method
635-------------------------
636
Georg Brandlc9007082011-01-09 09:04:08 +0000637.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
638 [const], [default], [type], [choices], [required], \
639 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000640
Georg Brandl69518bc2011-04-16 16:44:54 +0200641 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000642 has its own more detailed description below, but in short they are:
643
644 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300645 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000646
647 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200648 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000649
650 * nargs_ - The number of command-line arguments that should be consumed.
651
652 * const_ - A constant value required by some action_ and nargs_ selections.
653
654 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200655 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000656
Ezio Melotti2409d772011-04-16 23:13:50 +0300657 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000658
659 * choices_ - A container of the allowable values for the argument.
660
661 * required_ - Whether or not the command-line option may be omitted
662 (optionals only).
663
664 * help_ - A brief description of what the argument does.
665
666 * metavar_ - A name for the argument in usage messages.
667
668 * dest_ - The name of the attribute to be added to the object returned by
669 :meth:`parse_args`.
670
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000671The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000672
Georg Brandle0bf91d2010-10-17 10:34:28 +0000673
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000674name or flags
675^^^^^^^^^^^^^
676
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300677The :meth:`~ArgumentParser.add_argument` method must know whether an optional
678argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
679filenames, is expected. The first arguments passed to
680:meth:`~ArgumentParser.add_argument` must therefore be either a series of
681flags, or a simple argument name. For example, an optional argument could
682be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000683
684 >>> parser.add_argument('-f', '--foo')
685
686while a positional argument could be created like::
687
688 >>> parser.add_argument('bar')
689
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300690When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
691identified by the ``-`` prefix, and the remaining arguments will be assumed to
692be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000693
694 >>> parser = argparse.ArgumentParser(prog='PROG')
695 >>> parser.add_argument('-f', '--foo')
696 >>> parser.add_argument('bar')
697 >>> parser.parse_args(['BAR'])
698 Namespace(bar='BAR', foo=None)
699 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
700 Namespace(bar='BAR', foo='FOO')
701 >>> parser.parse_args(['--foo', 'FOO'])
702 usage: PROG [-h] [-f FOO] bar
703 PROG: error: too few arguments
704
Georg Brandle0bf91d2010-10-17 10:34:28 +0000705
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000706action
707^^^^^^
708
Éric Araujod9d7bca2011-08-10 04:19:03 +0200709:class:`ArgumentParser` objects associate command-line arguments with actions. These
710actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000711them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300712:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -0500713how the command-line arguments should be handled. The supplied actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000714
715* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300716 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000717
718 >>> parser = argparse.ArgumentParser()
719 >>> parser.add_argument('--foo')
720 >>> parser.parse_args('--foo 1'.split())
721 Namespace(foo='1')
722
723* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panterb4912b82016-04-09 03:49:48 +0000724 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300725 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000726
727 >>> parser = argparse.ArgumentParser()
728 >>> parser.add_argument('--foo', action='store_const', const=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000729 >>> parser.parse_args(['--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000730 Namespace(foo=42)
731
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800732* ``'store_true'`` and ``'store_false'`` - These are special cases of
733 ``'store_const'`` used for storing the values ``True`` and ``False``
734 respectively. In addition, they create default values of ``False`` and
735 ``True`` respectively. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000736
737 >>> parser = argparse.ArgumentParser()
738 >>> parser.add_argument('--foo', action='store_true')
739 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800740 >>> parser.add_argument('--baz', action='store_false')
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000741 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettingerf9cddcc2011-11-20 11:05:23 -0800742 Namespace(foo=True, bar=False, baz=True)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000743
744* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000745 list. This is useful to allow an option to be specified multiple times.
746 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000747
748 >>> parser = argparse.ArgumentParser()
749 >>> parser.add_argument('--foo', action='append')
750 >>> parser.parse_args('--foo 1 --foo 2'.split())
751 Namespace(foo=['1', '2'])
752
753* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000754 the const_ keyword argument to the list. (Note that the const_ keyword
755 argument defaults to ``None``.) The ``'append_const'`` action is typically
756 useful when multiple arguments need to store constants to the same list. For
757 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000758
759 >>> parser = argparse.ArgumentParser()
760 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
761 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
762 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200763 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000764
Sandro Tosi98492a52012-01-04 23:25:04 +0100765* ``'count'`` - This counts the number of times a keyword argument occurs. For
766 example, this is useful for increasing verbosity levels::
767
768 >>> parser = argparse.ArgumentParser()
769 >>> parser.add_argument('--verbose', '-v', action='count')
Martin Panterf5e60482016-04-26 11:41:25 +0000770 >>> parser.parse_args(['-vvv'])
Sandro Tosi98492a52012-01-04 23:25:04 +0100771 Namespace(verbose=3)
772
773* ``'help'`` - This prints a complete help message for all the options in the
774 current parser and then exits. By default a help action is automatically
775 added to the parser. See :class:`ArgumentParser` for details of how the
776 output is created.
777
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000778* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300779 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujoc3ef0372012-02-20 01:44:55 +0100780 and exits when invoked::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000781
782 >>> import argparse
783 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000784 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
785 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000786 PROG 2.0
787
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400788You may also specify an arbitrary action by passing an Action subclass or
789other object that implements the same interface. The recommended way to do
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400790this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400791and optionally the ``__init__`` method.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000792
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000793An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000794
795 >>> class FooAction(argparse.Action):
Jason R. Coombseb0ef412014-07-20 10:52:46 -0400796 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
797 ... if nargs is not None:
798 ... raise ValueError("nargs not allowed")
799 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000800 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000801 ... print('%r %r %r' % (namespace, values, option_string))
802 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000803 ...
804 >>> parser = argparse.ArgumentParser()
805 >>> parser.add_argument('--foo', action=FooAction)
806 >>> parser.add_argument('bar', action=FooAction)
807 >>> args = parser.parse_args('1 --foo 2'.split())
808 Namespace(bar=None, foo=None) '1' None
809 Namespace(bar='1', foo=None) '2' '--foo'
810 >>> args
811 Namespace(bar='1', foo='2')
812
Jason R. Coombs79690ac2014-08-03 14:54:11 -0400813For more details, see :class:`Action`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000814
815nargs
816^^^^^
817
818ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000819single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300820different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000821values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000822
Éric Araujoc3ef0372012-02-20 01:44:55 +0100823* ``N`` (an integer). ``N`` arguments from the command line will be gathered
824 together into a list. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000825
Georg Brandl682d7e02010-10-06 10:26:05 +0000826 >>> parser = argparse.ArgumentParser()
827 >>> parser.add_argument('--foo', nargs=2)
828 >>> parser.add_argument('bar', nargs=1)
829 >>> parser.parse_args('c --foo a b'.split())
830 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000831
Georg Brandl682d7e02010-10-06 10:26:05 +0000832 Note that ``nargs=1`` produces a list of one item. This is different from
833 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000834
Éric Araujofde92422011-08-19 01:30:26 +0200835* ``'?'``. One argument will be consumed from the command line if possible, and
836 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000837 default_ will be produced. Note that for optional arguments, there is an
838 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200839 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000840 examples to illustrate this::
841
842 >>> parser = argparse.ArgumentParser()
843 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
844 >>> parser.add_argument('bar', nargs='?', default='d')
Martin Panterf5e60482016-04-26 11:41:25 +0000845 >>> parser.parse_args(['XX', '--foo', 'YY'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000846 Namespace(bar='XX', foo='YY')
Martin Panterf5e60482016-04-26 11:41:25 +0000847 >>> parser.parse_args(['XX', '--foo'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000848 Namespace(bar='XX', foo='c')
Martin Panterf5e60482016-04-26 11:41:25 +0000849 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000850 Namespace(bar='d', foo='d')
851
852 One of the more common uses of ``nargs='?'`` is to allow optional input and
853 output files::
854
855 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000856 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
857 ... default=sys.stdin)
858 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
859 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000860 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000861 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
862 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000863 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000864 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
865 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000866
Éric Araujod9d7bca2011-08-10 04:19:03 +0200867* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000868 it generally doesn't make much sense to have more than one positional argument
869 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
870 possible. For example::
871
872 >>> parser = argparse.ArgumentParser()
873 >>> parser.add_argument('--foo', nargs='*')
874 >>> parser.add_argument('--bar', nargs='*')
875 >>> parser.add_argument('baz', nargs='*')
876 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
877 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
878
879* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
880 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200881 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000882
883 >>> parser = argparse.ArgumentParser(prog='PROG')
884 >>> parser.add_argument('foo', nargs='+')
Martin Panterf5e60482016-04-26 11:41:25 +0000885 >>> parser.parse_args(['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000886 Namespace(foo=['a', 'b'])
Martin Panterf5e60482016-04-26 11:41:25 +0000887 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000888 usage: PROG [-h] foo [foo ...]
889 PROG: error: too few arguments
890
Sandro Tosida8e11a2012-01-19 22:23:00 +0100891* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
892 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujoc3ef0372012-02-20 01:44:55 +0100893 to other command line utilities::
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100894
895 >>> parser = argparse.ArgumentParser(prog='PROG')
896 >>> parser.add_argument('--foo')
897 >>> parser.add_argument('command')
898 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosi04676862012-02-19 19:54:00 +0100899 >>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Sandro Tosida8e11a2012-01-19 22:23:00 +0100900 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100901
Éric Araujod9d7bca2011-08-10 04:19:03 +0200902If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200903is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000904will be consumed and a single item (not a list) will be produced.
905
906
907const
908^^^^^
909
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300910The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
911constant values that are not read from the command line but are required for
912the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000913
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300914* When :meth:`~ArgumentParser.add_argument` is called with
915 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujoc3ef0372012-02-20 01:44:55 +0100916 ``const`` value to one of the attributes of the object returned by
917 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000918
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300919* When :meth:`~ArgumentParser.add_argument` is called with option strings
920 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200921 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300922 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200923 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300924 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000925
Martin Panterb4912b82016-04-09 03:49:48 +0000926With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panter119e5022016-04-16 09:28:57 +0000927keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000928
929
930default
931^^^^^^^
932
933All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300934command line. The ``default`` keyword argument of
935:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200936specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300937For optional arguments, the ``default`` value is used when the option string
938was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000939
940 >>> parser = argparse.ArgumentParser()
941 >>> parser.add_argument('--foo', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000942 >>> parser.parse_args(['--foo', '2'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000943 Namespace(foo='2')
Martin Panterf5e60482016-04-26 11:41:25 +0000944 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000945 Namespace(foo=42)
946
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400947If the ``default`` value is a string, the parser parses the value as if it
948were a command-line argument. In particular, the parser applies any type_
949conversion argument, if provided, before setting the attribute on the
950:class:`Namespace` return value. Otherwise, the parser uses the value as is::
951
952 >>> parser = argparse.ArgumentParser()
953 >>> parser.add_argument('--length', default='10', type=int)
954 >>> parser.add_argument('--width', default=10.5, type=int)
955 >>> parser.parse_args()
956 Namespace(length=10, width=10.5)
957
Éric Araujo543edbd2011-08-19 01:45:12 +0200958For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200959is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000960
961 >>> parser = argparse.ArgumentParser()
962 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panterf5e60482016-04-26 11:41:25 +0000963 >>> parser.parse_args(['a'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000964 Namespace(foo='a')
Martin Panterf5e60482016-04-26 11:41:25 +0000965 >>> parser.parse_args([])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000966 Namespace(foo=42)
967
968
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000969Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
970command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000971
972 >>> parser = argparse.ArgumentParser()
973 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
974 >>> parser.parse_args([])
975 Namespace()
976 >>> parser.parse_args(['--foo', '1'])
977 Namespace(foo='1')
978
979
980type
981^^^^
982
Éric Araujod9d7bca2011-08-10 04:19:03 +0200983By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300984strings. However, quite often the command-line string should instead be
985interpreted as another type, like a :class:`float` or :class:`int`. The
986``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200987necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300988types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000989
990 >>> parser = argparse.ArgumentParser()
991 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000992 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000993 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000994 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000995
Barry Warsaw1dedd0a2012-09-25 10:37:58 -0400996See the section on the default_ keyword argument for information on when the
997``type`` argument is applied to default arguments.
998
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000999To ease the use of various types of files, the argparse module provides the
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001000factory FileType which takes the ``mode=``, ``bufsize=``, ``encoding=`` and
1001``errors=`` arguments of the :func:`open` function. For example,
1002``FileType('w')`` can be used to create a writable file::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001003
1004 >>> parser = argparse.ArgumentParser()
1005 >>> parser.add_argument('bar', type=argparse.FileType('w'))
1006 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +00001007 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001008
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001009``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +02001010the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001011
1012 >>> def perfect_square(string):
1013 ... value = int(string)
1014 ... sqrt = math.sqrt(value)
1015 ... if sqrt != int(sqrt):
1016 ... msg = "%r is not a perfect square" % string
1017 ... raise argparse.ArgumentTypeError(msg)
1018 ... return value
1019 ...
1020 >>> parser = argparse.ArgumentParser(prog='PROG')
1021 >>> parser.add_argument('foo', type=perfect_square)
Martin Panterf5e60482016-04-26 11:41:25 +00001022 >>> parser.parse_args(['9'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001023 Namespace(foo=9)
Martin Panterf5e60482016-04-26 11:41:25 +00001024 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001025 usage: PROG [-h] foo
1026 PROG: error: argument foo: '7' is not a perfect square
1027
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001028The choices_ keyword argument may be more convenient for type checkers that
1029simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001030
1031 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +00001032 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Martin Panterf5e60482016-04-26 11:41:25 +00001033 >>> parser.parse_args(['7'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001034 Namespace(foo=7)
Martin Panterf5e60482016-04-26 11:41:25 +00001035 >>> parser.parse_args(['11'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001036 usage: PROG [-h] {5,6,7,8,9}
1037 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1038
1039See the choices_ section for more details.
1040
1041
1042choices
1043^^^^^^^
1044
Éric Araujod9d7bca2011-08-10 04:19:03 +02001045Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek174ef672013-01-11 19:26:44 -08001046These can be handled by passing a container object as the *choices* keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001047argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek174ef672013-01-11 19:26:44 -08001048parsed, argument values will be checked, and an error message will be displayed
1049if the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001050
Chris Jerdonek174ef672013-01-11 19:26:44 -08001051 >>> parser = argparse.ArgumentParser(prog='game.py')
1052 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1053 >>> parser.parse_args(['rock'])
1054 Namespace(move='rock')
1055 >>> parser.parse_args(['fire'])
1056 usage: game.py [-h] {rock,paper,scissors}
1057 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1058 'paper', 'scissors')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001059
Chris Jerdonek174ef672013-01-11 19:26:44 -08001060Note that inclusion in the *choices* container is checked after any type_
1061conversions have been performed, so the type of the objects in the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001062container should match the type_ specified::
1063
Chris Jerdonek174ef672013-01-11 19:26:44 -08001064 >>> parser = argparse.ArgumentParser(prog='doors.py')
1065 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1066 >>> print(parser.parse_args(['3']))
1067 Namespace(door=3)
1068 >>> parser.parse_args(['4'])
1069 usage: doors.py [-h] {1,2,3}
1070 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001071
Chris Jerdonek174ef672013-01-11 19:26:44 -08001072Any object that supports the ``in`` operator can be passed as the *choices*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001073value, so :class:`dict` objects, :class:`set` objects, custom containers,
1074etc. are all supported.
1075
1076
1077required
1078^^^^^^^^
1079
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001080In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001081indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001082To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001083keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001084
1085 >>> parser = argparse.ArgumentParser()
1086 >>> parser.add_argument('--foo', required=True)
1087 >>> parser.parse_args(['--foo', 'BAR'])
1088 Namespace(foo='BAR')
1089 >>> parser.parse_args([])
1090 usage: argparse.py [-h] [--foo FOO]
1091 argparse.py: error: option --foo is required
1092
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001093As the example shows, if an option is marked as ``required``,
1094:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1095present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001096
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001097.. note::
1098
1099 Required options are generally considered bad form because users expect
1100 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001101
1102
1103help
1104^^^^
1105
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001106The ``help`` value is a string containing a brief description of the argument.
1107When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001108command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001109argument::
1110
1111 >>> parser = argparse.ArgumentParser(prog='frobble')
1112 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001113 ... help='foo the bars before frobbling')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001114 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchakadba90392016-05-10 12:01:23 +03001115 ... help='one of the bars to be frobbled')
Martin Panterf5e60482016-04-26 11:41:25 +00001116 >>> parser.parse_args(['-h'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001117 usage: frobble [-h] [--foo] bar [bar ...]
1118
1119 positional arguments:
1120 bar one of the bars to be frobbled
1121
1122 optional arguments:
1123 -h, --help show this help message and exit
1124 --foo foo the bars before frobbling
1125
1126The ``help`` strings can include various format specifiers to avoid repetition
1127of things like the program name or the argument default_. The available
1128specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001129:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001130
1131 >>> parser = argparse.ArgumentParser(prog='frobble')
1132 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001133 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001134 >>> parser.print_help()
1135 usage: frobble [-h] [bar]
1136
1137 positional arguments:
1138 bar the bar to frobble (default: 42)
1139
1140 optional arguments:
1141 -h, --help show this help message and exit
1142
Senthil Kumaranf21804a2012-06-26 14:17:19 +08001143As the help string supports %-formatting, if you want a literal ``%`` to appear
1144in the help string, you must escape it as ``%%``.
1145
Sandro Tosiea320ab2012-01-03 18:37:03 +01001146:mod:`argparse` supports silencing the help entry for certain options, by
1147setting the ``help`` value to ``argparse.SUPPRESS``::
1148
1149 >>> parser = argparse.ArgumentParser(prog='frobble')
1150 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1151 >>> parser.print_help()
1152 usage: frobble [-h]
1153
1154 optional arguments:
1155 -h, --help show this help message and exit
1156
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001157
1158metavar
1159^^^^^^^
1160
Sandro Tosi32587fb2013-01-11 10:49:00 +01001161When :class:`ArgumentParser` generates help messages, it needs some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001162to each expected argument. By default, ArgumentParser objects use the dest_
1163value as the "name" of each object. By default, for positional argument
1164actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001165the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001166``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001167optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001168will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001169
1170 >>> parser = argparse.ArgumentParser()
1171 >>> parser.add_argument('--foo')
1172 >>> parser.add_argument('bar')
1173 >>> parser.parse_args('X --foo Y'.split())
1174 Namespace(bar='X', foo='Y')
1175 >>> parser.print_help()
1176 usage: [-h] [--foo FOO] bar
1177
1178 positional arguments:
1179 bar
1180
1181 optional arguments:
1182 -h, --help show this help message and exit
1183 --foo FOO
1184
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001185An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001186
1187 >>> parser = argparse.ArgumentParser()
1188 >>> parser.add_argument('--foo', metavar='YYY')
1189 >>> parser.add_argument('bar', metavar='XXX')
1190 >>> parser.parse_args('X --foo Y'.split())
1191 Namespace(bar='X', foo='Y')
1192 >>> parser.print_help()
1193 usage: [-h] [--foo YYY] XXX
1194
1195 positional arguments:
1196 XXX
1197
1198 optional arguments:
1199 -h, --help show this help message and exit
1200 --foo YYY
1201
1202Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001203attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1204by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001205
1206Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001207Providing a tuple to ``metavar`` specifies a different display for each of the
1208arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001209
1210 >>> parser = argparse.ArgumentParser(prog='PROG')
1211 >>> parser.add_argument('-x', nargs=2)
1212 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1213 >>> parser.print_help()
1214 usage: PROG [-h] [-x X X] [--foo bar baz]
1215
1216 optional arguments:
1217 -h, --help show this help message and exit
1218 -x X X
1219 --foo bar baz
1220
1221
1222dest
1223^^^^
1224
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001225Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001226object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1227attribute is determined by the ``dest`` keyword argument of
1228:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1229``dest`` is normally supplied as the first argument to
1230:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001231
1232 >>> parser = argparse.ArgumentParser()
1233 >>> parser.add_argument('bar')
Martin Panterf5e60482016-04-26 11:41:25 +00001234 >>> parser.parse_args(['XXX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001235 Namespace(bar='XXX')
1236
1237For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001238the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001239taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001240string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001241the first short option string by stripping the initial ``-`` character. Any
1242internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001243the string is a valid attribute name. The examples below illustrate this
1244behavior::
1245
1246 >>> parser = argparse.ArgumentParser()
1247 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1248 >>> parser.add_argument('-x', '-y')
1249 >>> parser.parse_args('-f 1 -x 2'.split())
1250 Namespace(foo_bar='1', x='2')
1251 >>> parser.parse_args('--foo 1 -y 2'.split())
1252 Namespace(foo_bar='1', x='2')
1253
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001254``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001255
1256 >>> parser = argparse.ArgumentParser()
1257 >>> parser.add_argument('--foo', dest='bar')
1258 >>> parser.parse_args('--foo XXX'.split())
1259 Namespace(bar='XXX')
1260
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001261Action classes
1262^^^^^^^^^^^^^^
1263
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001264Action classes implement the Action API, a callable which returns a callable
1265which processes arguments from the command-line. Any object which follows
1266this API may be passed as the ``action`` parameter to
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001267:meth:`add_argument`.
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001268
Terry Jan Reedyee558262014-08-23 22:21:47 -04001269.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1270 type=None, choices=None, required=False, help=None, \
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001271 metavar=None)
1272
1273Action objects are used by an ArgumentParser to represent the information
1274needed to parse a single argument from one or more strings from the
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001275command line. The Action class must accept the two positional arguments
Raymond Hettingerc0de59b2014-08-03 23:44:30 -07001276plus any keyword arguments passed to :meth:`ArgumentParser.add_argument`
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001277except for the ``action`` itself.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001278
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001279Instances of Action (or return value of any callable to the ``action``
1280parameter) should have attributes "dest", "option_strings", "default", "type",
1281"required", "help", etc. defined. The easiest way to ensure these attributes
1282are defined is to call ``Action.__init__``.
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001283
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001284Action instances should be callable, so subclasses must override the
1285``__call__`` method, which should accept four parameters:
Jason R. Coombsf28cf7a2011-12-13 23:36:45 -05001286
1287* ``parser`` - The ArgumentParser object which contains this action.
1288
1289* ``namespace`` - The :class:`Namespace` object that will be returned by
1290 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1291 object using :func:`setattr`.
1292
1293* ``values`` - The associated command-line arguments, with any type conversions
1294 applied. Type conversions are specified with the type_ keyword argument to
1295 :meth:`~ArgumentParser.add_argument`.
1296
1297* ``option_string`` - The option string that was used to invoke this action.
1298 The ``option_string`` argument is optional, and will be absent if the action
1299 is associated with a positional argument.
1300
Jason R. Coombseb0ef412014-07-20 10:52:46 -04001301The ``__call__`` method may perform arbitrary actions, but will typically set
1302attributes on the ``namespace`` based on ``dest`` and ``values``.
1303
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001304
1305The parse_args() method
1306-----------------------
1307
Georg Brandle0bf91d2010-10-17 10:34:28 +00001308.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001309
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001310 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001311 namespace. Return the populated namespace.
1312
1313 Previous calls to :meth:`add_argument` determine exactly what objects are
1314 created and how they are assigned. See the documentation for
1315 :meth:`add_argument` for details.
1316
Éric Araujofde92422011-08-19 01:30:26 +02001317 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001318 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001319
Georg Brandle0bf91d2010-10-17 10:34:28 +00001320
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001321Option value syntax
1322^^^^^^^^^^^^^^^^^^^
1323
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001324The :meth:`~ArgumentParser.parse_args` method supports several ways of
1325specifying the value of an option (if it takes one). In the simplest case, the
1326option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001327
1328 >>> parser = argparse.ArgumentParser(prog='PROG')
1329 >>> parser.add_argument('-x')
1330 >>> parser.add_argument('--foo')
Martin Panterf5e60482016-04-26 11:41:25 +00001331 >>> parser.parse_args(['-x', 'X'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001332 Namespace(foo=None, x='X')
Martin Panterf5e60482016-04-26 11:41:25 +00001333 >>> parser.parse_args(['--foo', 'FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001334 Namespace(foo='FOO', x=None)
1335
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001336For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001337and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001338separate them::
1339
Martin Panterf5e60482016-04-26 11:41:25 +00001340 >>> parser.parse_args(['--foo=FOO'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001341 Namespace(foo='FOO', x=None)
1342
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001343For short options (options only one character long), the option and its value
1344can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001345
Martin Panterf5e60482016-04-26 11:41:25 +00001346 >>> parser.parse_args(['-xX'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001347 Namespace(foo=None, x='X')
1348
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001349Several short options can be joined together, using only a single ``-`` prefix,
1350as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001351
1352 >>> parser = argparse.ArgumentParser(prog='PROG')
1353 >>> parser.add_argument('-x', action='store_true')
1354 >>> parser.add_argument('-y', action='store_true')
1355 >>> parser.add_argument('-z')
Martin Panterf5e60482016-04-26 11:41:25 +00001356 >>> parser.parse_args(['-xyzZ'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001357 Namespace(x=True, y=True, z='Z')
1358
1359
1360Invalid arguments
1361^^^^^^^^^^^^^^^^^
1362
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001363While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1364variety of errors, including ambiguous options, invalid types, invalid options,
1365wrong number of positional arguments, etc. When it encounters such an error,
1366it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001367
1368 >>> parser = argparse.ArgumentParser(prog='PROG')
1369 >>> parser.add_argument('--foo', type=int)
1370 >>> parser.add_argument('bar', nargs='?')
1371
1372 >>> # invalid type
1373 >>> parser.parse_args(['--foo', 'spam'])
1374 usage: PROG [-h] [--foo FOO] [bar]
1375 PROG: error: argument --foo: invalid int value: 'spam'
1376
1377 >>> # invalid option
1378 >>> parser.parse_args(['--bar'])
1379 usage: PROG [-h] [--foo FOO] [bar]
1380 PROG: error: no such option: --bar
1381
1382 >>> # wrong number of arguments
1383 >>> parser.parse_args(['spam', 'badger'])
1384 usage: PROG [-h] [--foo FOO] [bar]
1385 PROG: error: extra arguments found: badger
1386
1387
Éric Araujo543edbd2011-08-19 01:45:12 +02001388Arguments containing ``-``
1389^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001390
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001391The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1392the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001393ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001394attempt to specify an option or an attempt to provide a positional argument.
1395The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001396arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001397there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001398
1399 >>> parser = argparse.ArgumentParser(prog='PROG')
1400 >>> parser.add_argument('-x')
1401 >>> parser.add_argument('foo', nargs='?')
1402
1403 >>> # no negative number options, so -1 is a positional argument
1404 >>> parser.parse_args(['-x', '-1'])
1405 Namespace(foo=None, x='-1')
1406
1407 >>> # no negative number options, so -1 and -5 are positional arguments
1408 >>> parser.parse_args(['-x', '-1', '-5'])
1409 Namespace(foo='-5', x='-1')
1410
1411 >>> parser = argparse.ArgumentParser(prog='PROG')
1412 >>> parser.add_argument('-1', dest='one')
1413 >>> parser.add_argument('foo', nargs='?')
1414
1415 >>> # negative number options present, so -1 is an option
1416 >>> parser.parse_args(['-1', 'X'])
1417 Namespace(foo=None, one='X')
1418
1419 >>> # negative number options present, so -2 is an option
1420 >>> parser.parse_args(['-2'])
1421 usage: PROG [-h] [-1 ONE] [foo]
1422 PROG: error: no such option: -2
1423
1424 >>> # negative number options present, so both -1s are options
1425 >>> parser.parse_args(['-1', '-1'])
1426 usage: PROG [-h] [-1 ONE] [foo]
1427 PROG: error: argument -1: expected one argument
1428
Éric Araujo543edbd2011-08-19 01:45:12 +02001429If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001430like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001431:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1432argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001433
1434 >>> parser.parse_args(['--', '-f'])
1435 Namespace(foo='-f', one=None)
1436
Eli Benderskyf3114532013-12-02 05:49:54 -08001437.. _prefix-matching:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001438
Eli Benderskyf3114532013-12-02 05:49:54 -08001439Argument abbreviations (prefix matching)
1440^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001441
Berker Peksag8089cd62015-02-14 01:39:17 +02001442The :meth:`~ArgumentParser.parse_args` method :ref:`by default <allow_abbrev>`
1443allows long options to be abbreviated to a prefix, if the abbreviation is
1444unambiguous (the prefix matches a unique option)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001445
1446 >>> parser = argparse.ArgumentParser(prog='PROG')
1447 >>> parser.add_argument('-bacon')
1448 >>> parser.add_argument('-badger')
1449 >>> parser.parse_args('-bac MMM'.split())
1450 Namespace(bacon='MMM', badger=None)
1451 >>> parser.parse_args('-bad WOOD'.split())
1452 Namespace(bacon=None, badger='WOOD')
1453 >>> parser.parse_args('-ba BA'.split())
1454 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1455 PROG: error: ambiguous option: -ba could match -badger, -bacon
1456
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001457An error is produced for arguments that could produce more than one options.
Berker Peksag8089cd62015-02-14 01:39:17 +02001458This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001459
1460
1461Beyond ``sys.argv``
1462^^^^^^^^^^^^^^^^^^^
1463
Éric Araujod9d7bca2011-08-10 04:19:03 +02001464Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001465of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001466:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1467interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001468
1469 >>> parser = argparse.ArgumentParser()
1470 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001471 ... 'integers', metavar='int', type=int, choices=range(10),
Serhiy Storchakadba90392016-05-10 12:01:23 +03001472 ... nargs='+', help='an integer in the range 0..9')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001473 >>> parser.add_argument(
1474 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchakadba90392016-05-10 12:01:23 +03001475 ... default=max, help='sum the integers (default: find the max)')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001476 >>> parser.parse_args(['1', '2', '3', '4'])
1477 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panterf5e60482016-04-26 11:41:25 +00001478 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001479 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1480
1481
Steven Bethardd8f2d502011-03-26 19:50:06 +01001482The Namespace object
1483^^^^^^^^^^^^^^^^^^^^
1484
Éric Araujo63b18a42011-07-29 17:59:17 +02001485.. class:: Namespace
1486
1487 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1488 an object holding attributes and return it.
1489
1490This class is deliberately simple, just an :class:`object` subclass with a
1491readable string representation. If you prefer to have dict-like view of the
1492attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001493
1494 >>> parser = argparse.ArgumentParser()
1495 >>> parser.add_argument('--foo')
1496 >>> args = parser.parse_args(['--foo', 'BAR'])
1497 >>> vars(args)
1498 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001499
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001500It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001501already existing object, rather than a new :class:`Namespace` object. This can
1502be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001503
Éric Araujo28053fb2010-11-22 03:09:19 +00001504 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001505 ... pass
1506 ...
1507 >>> c = C()
1508 >>> parser = argparse.ArgumentParser()
1509 >>> parser.add_argument('--foo')
1510 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1511 >>> c.foo
1512 'BAR'
1513
1514
1515Other utilities
1516---------------
1517
1518Sub-commands
1519^^^^^^^^^^^^
1520
Georg Brandlfc9a1132013-10-06 18:51:39 +02001521.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1522 [parser_class], [action], \
1523 [option_string], [dest], [help], \
1524 [metavar])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001525
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001526 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001527 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001528 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001529 this way can be a particularly good idea when a program performs several
1530 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001531 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001532 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti52336f02012-12-28 01:59:24 +02001533 called with no arguments and returns a special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001534 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1535 command name and any :class:`ArgumentParser` constructor arguments, and
1536 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001537
Georg Brandlfc9a1132013-10-06 18:51:39 +02001538 Description of parameters:
1539
1540 * title - title for the sub-parser group in help output; by default
1541 "subcommands" if description is provided, otherwise uses title for
1542 positional arguments
1543
1544 * description - description for the sub-parser group in help output, by
1545 default None
1546
1547 * prog - usage information that will be displayed with sub-command help,
1548 by default the name of the program and any positional arguments before the
1549 subparser argument
1550
1551 * parser_class - class which will be used to create sub-parser instances, by
1552 default the class of the current parser (e.g. ArgumentParser)
1553
Berker Peksag5a494f62015-01-20 06:45:53 +02001554 * action_ - the basic type of action to be taken when this argument is
1555 encountered at the command line
1556
1557 * dest_ - name of the attribute under which sub-command name will be
Georg Brandlfc9a1132013-10-06 18:51:39 +02001558 stored; by default None and no value is stored
1559
Berker Peksag5a494f62015-01-20 06:45:53 +02001560 * help_ - help for sub-parser group in help output, by default None
Georg Brandlfc9a1132013-10-06 18:51:39 +02001561
Berker Peksag5a494f62015-01-20 06:45:53 +02001562 * metavar_ - string presenting available sub-commands in help; by default it
Georg Brandlfc9a1132013-10-06 18:51:39 +02001563 is None and presents sub-commands in form {cmd1, cmd2, ..}
1564
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001565 Some example usage::
1566
1567 >>> # create the top-level parser
1568 >>> parser = argparse.ArgumentParser(prog='PROG')
1569 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1570 >>> subparsers = parser.add_subparsers(help='sub-command help')
1571 >>>
1572 >>> # create the parser for the "a" command
1573 >>> parser_a = subparsers.add_parser('a', help='a help')
1574 >>> parser_a.add_argument('bar', type=int, help='bar help')
1575 >>>
1576 >>> # create the parser for the "b" command
1577 >>> parser_b = subparsers.add_parser('b', help='b help')
1578 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1579 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001580 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001581 >>> parser.parse_args(['a', '12'])
1582 Namespace(bar=12, foo=False)
1583 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1584 Namespace(baz='Z', foo=True)
1585
1586 Note that the object returned by :meth:`parse_args` will only contain
1587 attributes for the main parser and the subparser that was selected by the
1588 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001589 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1590 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001591 ``baz`` attributes are present.
1592
1593 Similarly, when a help message is requested from a subparser, only the help
1594 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001595 include parent parser or sibling parser messages. (A help message for each
1596 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001597 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001598
1599 ::
1600
1601 >>> parser.parse_args(['--help'])
1602 usage: PROG [-h] [--foo] {a,b} ...
1603
1604 positional arguments:
1605 {a,b} sub-command help
Ezio Melotti7128e072013-01-12 10:39:45 +02001606 a a help
1607 b b help
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001608
1609 optional arguments:
1610 -h, --help show this help message and exit
1611 --foo foo help
1612
1613 >>> parser.parse_args(['a', '--help'])
1614 usage: PROG a [-h] bar
1615
1616 positional arguments:
1617 bar bar help
1618
1619 optional arguments:
1620 -h, --help show this help message and exit
1621
1622 >>> parser.parse_args(['b', '--help'])
1623 usage: PROG b [-h] [--baz {X,Y,Z}]
1624
1625 optional arguments:
1626 -h, --help show this help message and exit
1627 --baz {X,Y,Z} baz help
1628
1629 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1630 keyword arguments. When either is present, the subparser's commands will
1631 appear in their own group in the help output. For example::
1632
1633 >>> parser = argparse.ArgumentParser()
1634 >>> subparsers = parser.add_subparsers(title='subcommands',
1635 ... description='valid subcommands',
1636 ... help='additional help')
1637 >>> subparsers.add_parser('foo')
1638 >>> subparsers.add_parser('bar')
1639 >>> parser.parse_args(['-h'])
1640 usage: [-h] {foo,bar} ...
1641
1642 optional arguments:
1643 -h, --help show this help message and exit
1644
1645 subcommands:
1646 valid subcommands
1647
1648 {foo,bar} additional help
1649
Steven Bethardfd311a72010-12-18 11:19:23 +00001650 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1651 which allows multiple strings to refer to the same subparser. This example,
1652 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1653
1654 >>> parser = argparse.ArgumentParser()
1655 >>> subparsers = parser.add_subparsers()
1656 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1657 >>> checkout.add_argument('foo')
1658 >>> parser.parse_args(['co', 'bar'])
1659 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001660
1661 One particularly effective way of handling sub-commands is to combine the use
1662 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1663 that each subparser knows which Python function it should execute. For
1664 example::
1665
1666 >>> # sub-command functions
1667 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001668 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001669 ...
1670 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001671 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001672 ...
1673 >>> # create the top-level parser
1674 >>> parser = argparse.ArgumentParser()
1675 >>> subparsers = parser.add_subparsers()
1676 >>>
1677 >>> # create the parser for the "foo" command
1678 >>> parser_foo = subparsers.add_parser('foo')
1679 >>> parser_foo.add_argument('-x', type=int, default=1)
1680 >>> parser_foo.add_argument('y', type=float)
1681 >>> parser_foo.set_defaults(func=foo)
1682 >>>
1683 >>> # create the parser for the "bar" command
1684 >>> parser_bar = subparsers.add_parser('bar')
1685 >>> parser_bar.add_argument('z')
1686 >>> parser_bar.set_defaults(func=bar)
1687 >>>
1688 >>> # parse the args and call whatever function was selected
1689 >>> args = parser.parse_args('foo 1 -x 2'.split())
1690 >>> args.func(args)
1691 2.0
1692 >>>
1693 >>> # parse the args and call whatever function was selected
1694 >>> args = parser.parse_args('bar XYZYX'.split())
1695 >>> args.func(args)
1696 ((XYZYX))
1697
Steven Bethardfd311a72010-12-18 11:19:23 +00001698 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001699 appropriate function after argument parsing is complete. Associating
1700 functions with actions like this is typically the easiest way to handle the
1701 different actions for each of your subparsers. However, if it is necessary
1702 to check the name of the subparser that was invoked, the ``dest`` keyword
1703 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001704
1705 >>> parser = argparse.ArgumentParser()
1706 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1707 >>> subparser1 = subparsers.add_parser('1')
1708 >>> subparser1.add_argument('-x')
1709 >>> subparser2 = subparsers.add_parser('2')
1710 >>> subparser2.add_argument('y')
1711 >>> parser.parse_args(['2', 'frobble'])
1712 Namespace(subparser_name='2', y='frobble')
1713
1714
1715FileType objects
1716^^^^^^^^^^^^^^^^
1717
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001718.. class:: FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001719
1720 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001721 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001722 :class:`FileType` objects as their type will open command-line arguments as
1723 files with the requested modes, buffer sizes, encodings and error handling
1724 (see the :func:`open` function for more details)::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001725
Éric Araujoc3ef0372012-02-20 01:44:55 +01001726 >>> parser = argparse.ArgumentParser()
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001727 >>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
1728 >>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
1729 >>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
1730 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 +00001731
1732 FileType objects understand the pseudo-argument ``'-'`` and automatically
1733 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujoc3ef0372012-02-20 01:44:55 +01001734 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001735
Éric Araujoc3ef0372012-02-20 01:44:55 +01001736 >>> parser = argparse.ArgumentParser()
1737 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1738 >>> parser.parse_args(['-'])
1739 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001740
R David Murrayfced3ec2013-12-31 11:18:01 -05001741 .. versionadded:: 3.4
1742 The *encodings* and *errors* keyword arguments.
1743
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001744
1745Argument groups
1746^^^^^^^^^^^^^^^
1747
Georg Brandle0bf91d2010-10-17 10:34:28 +00001748.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001749
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001750 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001751 "positional arguments" and "optional arguments" when displaying help
1752 messages. When there is a better conceptual grouping of arguments than this
1753 default one, appropriate groups can be created using the
1754 :meth:`add_argument_group` method::
1755
1756 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1757 >>> group = parser.add_argument_group('group')
1758 >>> group.add_argument('--foo', help='foo help')
1759 >>> group.add_argument('bar', help='bar help')
1760 >>> parser.print_help()
1761 usage: PROG [--foo FOO] bar
1762
1763 group:
1764 bar bar help
1765 --foo FOO foo help
1766
1767 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001768 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1769 :class:`ArgumentParser`. When an argument is added to the group, the parser
1770 treats it just like a normal argument, but displays the argument in a
1771 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001772 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001773 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001774
1775 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1776 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1777 >>> group1.add_argument('foo', help='foo help')
1778 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1779 >>> group2.add_argument('--bar', help='bar help')
1780 >>> parser.print_help()
1781 usage: PROG [--bar BAR] foo
1782
1783 group1:
1784 group1 description
1785
1786 foo foo help
1787
1788 group2:
1789 group2 description
1790
1791 --bar BAR bar help
1792
Sandro Tosi99e7d072012-03-26 19:36:23 +02001793 Note that any arguments not in your user-defined groups will end up back
1794 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001795
1796
1797Mutual exclusion
1798^^^^^^^^^^^^^^^^
1799
Georg Brandled86ff82013-10-06 13:09:59 +02001800.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001801
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001802 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1803 one of the arguments in the mutually exclusive group was present on the
1804 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001805
1806 >>> parser = argparse.ArgumentParser(prog='PROG')
1807 >>> group = parser.add_mutually_exclusive_group()
1808 >>> group.add_argument('--foo', action='store_true')
1809 >>> group.add_argument('--bar', action='store_false')
1810 >>> parser.parse_args(['--foo'])
1811 Namespace(bar=True, foo=True)
1812 >>> parser.parse_args(['--bar'])
1813 Namespace(bar=False, foo=False)
1814 >>> parser.parse_args(['--foo', '--bar'])
1815 usage: PROG [-h] [--foo | --bar]
1816 PROG: error: argument --bar: not allowed with argument --foo
1817
Georg Brandle0bf91d2010-10-17 10:34:28 +00001818 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001819 argument, to indicate that at least one of the mutually exclusive arguments
1820 is required::
1821
1822 >>> parser = argparse.ArgumentParser(prog='PROG')
1823 >>> group = parser.add_mutually_exclusive_group(required=True)
1824 >>> group.add_argument('--foo', action='store_true')
1825 >>> group.add_argument('--bar', action='store_false')
1826 >>> parser.parse_args([])
1827 usage: PROG [-h] (--foo | --bar)
1828 PROG: error: one of the arguments --foo --bar is required
1829
1830 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001831 *title* and *description* arguments of
1832 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001833
1834
1835Parser defaults
1836^^^^^^^^^^^^^^^
1837
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001838.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001839
1840 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001841 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001842 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001843 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001844 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001845
1846 >>> parser = argparse.ArgumentParser()
1847 >>> parser.add_argument('foo', type=int)
1848 >>> parser.set_defaults(bar=42, baz='badger')
1849 >>> parser.parse_args(['736'])
1850 Namespace(bar=42, baz='badger', foo=736)
1851
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001852 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001853
1854 >>> parser = argparse.ArgumentParser()
1855 >>> parser.add_argument('--foo', default='bar')
1856 >>> parser.set_defaults(foo='spam')
1857 >>> parser.parse_args([])
1858 Namespace(foo='spam')
1859
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001860 Parser-level defaults can be particularly useful when working with multiple
1861 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1862 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001863
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001864.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001865
1866 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001867 :meth:`~ArgumentParser.add_argument` or by
1868 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001869
1870 >>> parser = argparse.ArgumentParser()
1871 >>> parser.add_argument('--foo', default='badger')
1872 >>> parser.get_default('foo')
1873 'badger'
1874
1875
1876Printing help
1877^^^^^^^^^^^^^
1878
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001879In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1880care of formatting and printing any usage or error messages. However, several
1881formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001882
Georg Brandle0bf91d2010-10-17 10:34:28 +00001883.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001884
1885 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001886 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001887 assumed.
1888
Georg Brandle0bf91d2010-10-17 10:34:28 +00001889.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001890
1891 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001892 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001893 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001894
1895There are also variants of these methods that simply return a string instead of
1896printing it:
1897
Georg Brandle0bf91d2010-10-17 10:34:28 +00001898.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001899
1900 Return a string containing a brief description of how the
1901 :class:`ArgumentParser` should be invoked on the command line.
1902
Georg Brandle0bf91d2010-10-17 10:34:28 +00001903.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001904
1905 Return a string containing a help message, including the program usage and
1906 information about the arguments registered with the :class:`ArgumentParser`.
1907
1908
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001909Partial parsing
1910^^^^^^^^^^^^^^^
1911
Georg Brandle0bf91d2010-10-17 10:34:28 +00001912.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001913
Georg Brandl69518bc2011-04-16 16:44:54 +02001914Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001915the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001916:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001917:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1918extra arguments are present. Instead, it returns a two item tuple containing
1919the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001920
1921::
1922
1923 >>> parser = argparse.ArgumentParser()
1924 >>> parser.add_argument('--foo', action='store_true')
1925 >>> parser.add_argument('bar')
1926 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1927 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1928
Eli Benderskyf3114532013-12-02 05:49:54 -08001929.. warning::
1930 :ref:`Prefix matching <prefix-matching>` rules apply to
1931 :meth:`parse_known_args`. The parser may consume an option even if it's just
1932 a prefix of one of its known options, instead of leaving it in the remaining
1933 arguments list.
1934
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001935
1936Customizing file parsing
1937^^^^^^^^^^^^^^^^^^^^^^^^
1938
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001939.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001940
Georg Brandle0bf91d2010-10-17 10:34:28 +00001941 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001942 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft8b852f12014-05-20 12:58:38 -04001943 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001944 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001945
Georg Brandle0bf91d2010-10-17 10:34:28 +00001946 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001947 the argument file. It returns a list of arguments parsed from this string.
1948 The method is called once per line read from the argument file, in order.
1949
1950 A useful override of this method is one that treats each space-separated word
1951 as an argument::
1952
1953 def convert_arg_line_to_args(self, arg_line):
Berker Peksag8c99a6d2015-04-26 12:09:54 +03001954 return arg_line.split()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001955
1956
Georg Brandl93754922010-10-17 10:28:04 +00001957Exiting methods
1958^^^^^^^^^^^^^^^
1959
1960.. method:: ArgumentParser.exit(status=0, message=None)
1961
1962 This method terminates the program, exiting with the specified *status*
1963 and, if given, it prints a *message* before that.
1964
1965.. method:: ArgumentParser.error(message)
1966
1967 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001968 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001969
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001970.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001971
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001972Upgrading optparse code
1973-----------------------
1974
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001975Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001976with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1977transparently, particularly with the changes required to support the new
1978``nargs=`` specifiers and better usage messages. When most everything in
1979:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1980longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001981
Berker Peksag6c1f0ad2014-09-26 15:34:26 +03001982The :mod:`argparse` module improves on the standard library :mod:`optparse`
1983module in a number of ways including:
1984
1985* Handling positional arguments.
1986* Supporting sub-commands.
1987* Allowing alternative option prefixes like ``+`` and ``/``.
1988* Handling zero-or-more and one-or-more style arguments.
1989* Producing more informative usage messages.
1990* Providing a much simpler interface for custom ``type`` and ``action``.
1991
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001992A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001993
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001994* Replace all :meth:`optparse.OptionParser.add_option` calls with
1995 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001996
R David Murray5e0c5712012-03-30 18:07:42 -04001997* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001998 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5e0c5712012-03-30 18:07:42 -04001999 calls for the positional arguments. Keep in mind that what was previously
2000 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002001
2002* Replace callback actions and the ``callback_*`` keyword arguments with
2003 ``type`` or ``action`` arguments.
2004
2005* Replace string names for ``type`` keyword arguments with the corresponding
2006 type objects (e.g. int, float, complex, etc).
2007
Benjamin Peterson98047eb2010-03-03 02:07:08 +00002008* Replace :class:`optparse.Values` with :class:`Namespace` and
2009 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
2010 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002011
2012* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03002013 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002014 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00002015
2016* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panterd21e0b52015-10-10 10:36:22 +00002017 ``parser.add_argument('--version', action='version', version='<the version>')``.