blob: 1ea1f3fc1a564ad41face5c5f1e20588507ebae2 [file] [log] [blame]
Ezio Melotti12125822011-04-16 23:04:51 +03001:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
Georg Brandlb8d0e362010-11-26 07:53:50 +00002===============================================================================
Benjamin Petersona39e9662010-03-02 22:05:59 +00003
4.. module:: argparse
Éric Araujo67719bd2011-08-19 02:00:07 +02005 :synopsis: Command-line option and argument parsing library.
Benjamin Petersona39e9662010-03-02 22:05:59 +00006.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
Benjamin Petersona39e9662010-03-02 22:05:59 +00007.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
8
Éric Araujo29a0b572011-08-19 02:14:03 +02009.. versionadded:: 2.7
10
11**Source code:** :source:`Lib/argparse.py`
12
13--------------
Benjamin Petersona39e9662010-03-02 22:05:59 +000014
Ezio Melottie48daea2012-05-06 16:15:35 +030015.. sidebar:: Tutorial
16
17 This page contains the API reference information. For a more gentle
18 introduction to Python command-line parsing, have a look at the
19 :ref:`argparse tutorial <argparse-tutorial>`.
20
Ezio Melotti12125822011-04-16 23:04:51 +030021The :mod:`argparse` module makes it easy to write user-friendly command-line
Benjamin Peterson90c58022010-03-03 01:55:09 +000022interfaces. The program defines what arguments it requires, and :mod:`argparse`
Georg Brandld2decd92010-03-02 22:17:38 +000023will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson90c58022010-03-03 01:55:09 +000024module also automatically generates help and usage messages and issues errors
25when users give the program invalid arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +000026
Georg Brandlb8d0e362010-11-26 07:53:50 +000027
Benjamin Petersona39e9662010-03-02 22:05:59 +000028Example
29-------
30
Benjamin Peterson90c58022010-03-03 01:55:09 +000031The following code is a Python program that takes a list of integers and
32produces either the sum or the max::
Benjamin Petersona39e9662010-03-02 22:05:59 +000033
34 import argparse
35
36 parser = argparse.ArgumentParser(description='Process some integers.')
37 parser.add_argument('integers', metavar='N', type=int, nargs='+',
Serhiy Storchaka12d547a2016-05-10 13:45:32 +030038 help='an integer for the accumulator')
Benjamin Petersona39e9662010-03-02 22:05:59 +000039 parser.add_argument('--sum', dest='accumulate', action='store_const',
Serhiy Storchaka12d547a2016-05-10 13:45:32 +030040 const=sum, default=max,
41 help='sum the integers (default: find the max)')
Benjamin Petersona39e9662010-03-02 22:05:59 +000042
43 args = parser.parse_args()
44 print args.accumulate(args.integers)
45
46Assuming the Python code above is saved into a file called ``prog.py``, it can
Martin Panter8f1dd222016-07-26 11:18:21 +020047be run at the command line and provides useful help messages:
48
49.. code-block:: shell-session
Benjamin Petersona39e9662010-03-02 22:05:59 +000050
Georg Brandl9f572782013-10-06 19:33:56 +020051 $ python prog.py -h
Benjamin Petersona39e9662010-03-02 22:05:59 +000052 usage: prog.py [-h] [--sum] N [N ...]
53
54 Process some integers.
55
56 positional arguments:
57 N an integer for the accumulator
58
59 optional arguments:
60 -h, --help show this help message and exit
61 --sum sum the integers (default: find the max)
62
63When run with the appropriate arguments, it prints either the sum or the max of
Martin Panter8f1dd222016-07-26 11:18:21 +020064the command-line integers:
65
66.. code-block:: shell-session
Benjamin Petersona39e9662010-03-02 22:05:59 +000067
Georg Brandl9f572782013-10-06 19:33:56 +020068 $ python prog.py 1 2 3 4
Benjamin Petersona39e9662010-03-02 22:05:59 +000069 4
70
Georg Brandl9f572782013-10-06 19:33:56 +020071 $ python prog.py 1 2 3 4 --sum
Benjamin Petersona39e9662010-03-02 22:05:59 +000072 10
73
Martin Panter8f1dd222016-07-26 11:18:21 +020074If invalid arguments are passed in, it will issue an error:
75
76.. code-block:: shell-session
Benjamin Petersona39e9662010-03-02 22:05:59 +000077
Georg Brandl9f572782013-10-06 19:33:56 +020078 $ python prog.py a b c
Benjamin Petersona39e9662010-03-02 22:05:59 +000079 usage: prog.py [-h] [--sum] N [N ...]
80 prog.py: error: argument N: invalid int value: 'a'
81
82The following sections walk you through this example.
83
Georg Brandlb8d0e362010-11-26 07:53:50 +000084
Benjamin Petersona39e9662010-03-02 22:05:59 +000085Creating a parser
86^^^^^^^^^^^^^^^^^
87
Benjamin Petersonac80c152010-03-03 21:28:25 +000088The first step in using the :mod:`argparse` is creating an
Benjamin Peterson90c58022010-03-03 01:55:09 +000089:class:`ArgumentParser` object::
Benjamin Petersona39e9662010-03-02 22:05:59 +000090
91 >>> parser = argparse.ArgumentParser(description='Process some integers.')
92
93The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotti2eab88e2011-04-21 15:26:46 +030094parse the command line into Python data types.
Benjamin Petersona39e9662010-03-02 22:05:59 +000095
96
97Adding arguments
98^^^^^^^^^^^^^^^^
99
Benjamin Peterson90c58022010-03-03 01:55:09 +0000100Filling an :class:`ArgumentParser` with information about program arguments is
101done by making calls to the :meth:`~ArgumentParser.add_argument` method.
102Generally, these calls tell the :class:`ArgumentParser` how to take the strings
103on the command line and turn them into objects. This information is stored and
104used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000105
106 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
107 ... help='an integer for the accumulator')
108 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
109 ... const=sum, default=max,
110 ... help='sum the integers (default: find the max)')
111
Ezio Melottic69313a2011-04-22 01:29:13 +0300112Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Georg Brandld2decd92010-03-02 22:17:38 +0000113two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
114will be a list of one or more ints, and the ``accumulate`` attribute will be
115either the :func:`sum` function, if ``--sum`` was specified at the command line,
116or the :func:`max` function if it was not.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000117
Georg Brandlb8d0e362010-11-26 07:53:50 +0000118
Benjamin Petersona39e9662010-03-02 22:05:59 +0000119Parsing arguments
120^^^^^^^^^^^^^^^^^
121
Éric Araujo67719bd2011-08-19 02:00:07 +0200122:class:`ArgumentParser` parses arguments through the
Ezio Melotti12125822011-04-16 23:04:51 +0300123:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujo67719bd2011-08-19 02:00:07 +0200124convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujof0d44bc2011-07-29 17:59:17 +0200125In most cases, this means a simple :class:`Namespace` object will be built up from
Ezio Melotti12125822011-04-16 23:04:51 +0300126attributes parsed out of the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000127
128 >>> parser.parse_args(['--sum', '7', '-1', '42'])
129 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
130
Benjamin Peterson90c58022010-03-03 01:55:09 +0000131In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
132arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujo67719bd2011-08-19 02:00:07 +0200133command-line arguments from :data:`sys.argv`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000134
135
136ArgumentParser objects
137----------------------
138
Ezio Melottied3f5902012-09-14 06:48:32 +0300139.. class:: ArgumentParser(prog=None, usage=None, description=None, \
140 epilog=None, parents=[], \
141 formatter_class=argparse.HelpFormatter, \
142 prefix_chars='-', fromfile_prefix_chars=None, \
143 argument_default=None, conflict_handler='error', \
144 add_help=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000145
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300146 Create a new :class:`ArgumentParser` object. All parameters should be passed
147 as keyword arguments. Each parameter has its own more detailed description
148 below, but in short they are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000149
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300150 * prog_ - The name of the program (default: ``sys.argv[0]``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000151
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300152 * usage_ - The string describing the program usage (default: generated from
153 arguments added to parser)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000154
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300155 * description_ - Text to display before the argument help (default: none)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000156
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300157 * epilog_ - Text to display after the argument help (default: none)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000158
Benjamin Peterson90c58022010-03-03 01:55:09 +0000159 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300160 also be included
Benjamin Petersona39e9662010-03-02 22:05:59 +0000161
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300162 * formatter_class_ - A class for customizing the help output
163
164 * prefix_chars_ - The set of characters that prefix optional arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000165 (default: '-')
166
167 * fromfile_prefix_chars_ - The set of characters that prefix files from
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300168 which additional arguments should be read (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000169
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300170 * argument_default_ - The global default value for arguments
171 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000172
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300173 * conflict_handler_ - The strategy for resolving conflicting optionals
174 (usually unnecessary)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000175
Martin Panterc7496ee2017-01-14 08:51:49 +0000176 * add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000177
Benjamin Peterson90c58022010-03-03 01:55:09 +0000178The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000179
180
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300181prog
182^^^^
183
Martin Panterba5480b2016-09-08 05:39:59 +0000184By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300185how to display the name of the program in help messages. This default is almost
186always desirable because it will make the help messages match how the program was
187invoked on the command line. For example, consider a file named
188``myprogram.py`` with the following code::
189
190 import argparse
191 parser = argparse.ArgumentParser()
192 parser.add_argument('--foo', help='foo help')
193 args = parser.parse_args()
194
195The help for this program will display ``myprogram.py`` as the program name
Martin Panter8f1dd222016-07-26 11:18:21 +0200196(regardless of where the program was invoked from):
197
198.. code-block:: shell-session
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300199
200 $ python myprogram.py --help
201 usage: myprogram.py [-h] [--foo FOO]
202
203 optional arguments:
204 -h, --help show this help message and exit
205 --foo FOO foo help
206 $ cd ..
Martin Panterc7496ee2017-01-14 08:51:49 +0000207 $ python subdir/myprogram.py --help
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300208 usage: myprogram.py [-h] [--foo FOO]
209
210 optional arguments:
211 -h, --help show this help message and exit
212 --foo FOO foo help
213
214To change this default behavior, another value can be supplied using the
215``prog=`` argument to :class:`ArgumentParser`::
216
217 >>> parser = argparse.ArgumentParser(prog='myprogram')
218 >>> parser.print_help()
219 usage: myprogram [-h]
220
221 optional arguments:
222 -h, --help show this help message and exit
223
224Note that the program name, whether determined from ``sys.argv[0]`` or from the
225``prog=`` argument, is available to help messages using the ``%(prog)s`` format
226specifier.
227
228::
229
230 >>> parser = argparse.ArgumentParser(prog='myprogram')
231 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
232 >>> parser.print_help()
233 usage: myprogram [-h] [--foo FOO]
234
235 optional arguments:
236 -h, --help show this help message and exit
237 --foo FOO foo of the myprogram program
238
239
240usage
241^^^^^
242
243By default, :class:`ArgumentParser` calculates the usage message from the
244arguments it contains::
245
246 >>> parser = argparse.ArgumentParser(prog='PROG')
247 >>> parser.add_argument('--foo', nargs='?', help='foo help')
248 >>> parser.add_argument('bar', nargs='+', help='bar help')
249 >>> parser.print_help()
250 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
251
252 positional arguments:
253 bar bar help
254
255 optional arguments:
256 -h, --help show this help message and exit
257 --foo [FOO] foo help
258
259The default message can be overridden with the ``usage=`` keyword argument::
260
261 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
262 >>> parser.add_argument('--foo', nargs='?', help='foo help')
263 >>> parser.add_argument('bar', nargs='+', help='bar help')
264 >>> parser.print_help()
265 usage: PROG [options]
266
267 positional arguments:
268 bar bar help
269
270 optional arguments:
271 -h, --help show this help message and exit
272 --foo [FOO] foo help
273
274The ``%(prog)s`` format specifier is available to fill in the program name in
275your usage messages.
276
277
Benjamin Petersona39e9662010-03-02 22:05:59 +0000278description
279^^^^^^^^^^^
280
Benjamin Peterson90c58022010-03-03 01:55:09 +0000281Most calls to the :class:`ArgumentParser` constructor will use the
282``description=`` keyword argument. This argument gives a brief description of
283what the program does and how it works. In help messages, the description is
284displayed between the command-line usage string and the help messages for the
285various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000286
287 >>> parser = argparse.ArgumentParser(description='A foo that bars')
288 >>> parser.print_help()
289 usage: argparse.py [-h]
290
291 A foo that bars
292
293 optional arguments:
294 -h, --help show this help message and exit
295
296By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000297given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000298
299
300epilog
301^^^^^^
302
303Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000304description of the arguments. Such text can be specified using the ``epilog=``
305argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000306
307 >>> parser = argparse.ArgumentParser(
308 ... description='A foo that bars',
309 ... epilog="And that's how you'd foo a bar")
310 >>> parser.print_help()
311 usage: argparse.py [-h]
312
313 A foo that bars
314
315 optional arguments:
316 -h, --help show this help message and exit
317
318 And that's how you'd foo a bar
319
320As with the description_ argument, the ``epilog=`` text is by default
321line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000322argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000323
324
Benjamin Petersona39e9662010-03-02 22:05:59 +0000325parents
326^^^^^^^
327
328Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000329repeating the definitions of these arguments, a single parser with all the
330shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
331can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
332objects, collects all the positional and optional actions from them, and adds
333these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000334
335 >>> parent_parser = argparse.ArgumentParser(add_help=False)
336 >>> parent_parser.add_argument('--parent', type=int)
337
338 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
339 >>> foo_parser.add_argument('foo')
340 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
341 Namespace(foo='XXX', parent=2)
342
343 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
344 >>> bar_parser.add_argument('--bar')
345 >>> bar_parser.parse_args(['--bar', 'YYY'])
346 Namespace(bar='YYY', parent=None)
347
Georg Brandld2decd92010-03-02 22:17:38 +0000348Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000349:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
350and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000351
Steven Bethard5e0062d2011-03-26 21:50:38 +0100352.. note::
353 You must fully initialize the parsers before passing them via ``parents=``.
354 If you change the parent parsers after the child parser, those changes will
355 not be reflected in the child.
356
Benjamin Petersona39e9662010-03-02 22:05:59 +0000357
358formatter_class
359^^^^^^^^^^^^^^^
360
Benjamin Peterson90c58022010-03-03 01:55:09 +0000361:class:`ArgumentParser` objects allow the help formatting to be customized by
362specifying an alternate formatting class. Currently, there are three such
Ezio Melottic69313a2011-04-22 01:29:13 +0300363classes:
364
365.. class:: RawDescriptionHelpFormatter
366 RawTextHelpFormatter
367 ArgumentDefaultsHelpFormatter
368
369The first two allow more control over how textual descriptions are displayed,
370while the last automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000371
Benjamin Peterson90c58022010-03-03 01:55:09 +0000372By default, :class:`ArgumentParser` objects line-wrap the description_ and
373epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000374
375 >>> parser = argparse.ArgumentParser(
376 ... prog='PROG',
377 ... description='''this description
378 ... was indented weird
379 ... but that is okay''',
380 ... epilog='''
381 ... likewise for this epilog whose whitespace will
382 ... be cleaned up and whose words will be wrapped
383 ... across a couple lines''')
384 >>> parser.print_help()
385 usage: PROG [-h]
386
387 this description was indented weird but that is okay
388
389 optional arguments:
390 -h, --help show this help message and exit
391
392 likewise for this epilog whose whitespace will be cleaned up and whose words
393 will be wrapped across a couple lines
394
Éric Araujo67719bd2011-08-19 02:00:07 +0200395Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000396indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000397should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000398
399 >>> parser = argparse.ArgumentParser(
400 ... prog='PROG',
401 ... formatter_class=argparse.RawDescriptionHelpFormatter,
402 ... description=textwrap.dedent('''\
403 ... Please do not mess up this text!
404 ... --------------------------------
405 ... I have indented it
406 ... exactly the way
407 ... I want it
408 ... '''))
409 >>> parser.print_help()
410 usage: PROG [-h]
411
412 Please do not mess up this text!
413 --------------------------------
414 I have indented it
415 exactly the way
416 I want it
417
418 optional arguments:
419 -h, --help show this help message and exit
420
Éric Araujo67719bd2011-08-19 02:00:07 +0200421:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson90c58022010-03-03 01:55:09 +0000422including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000423
Benjamin Peterson90c58022010-03-03 01:55:09 +0000424The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000425will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000426
427 >>> parser = argparse.ArgumentParser(
428 ... prog='PROG',
429 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
430 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
431 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
432 >>> parser.print_help()
433 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
434
435 positional arguments:
436 bar BAR! (default: [1, 2, 3])
437
438 optional arguments:
439 -h, --help show this help message and exit
440 --foo FOO FOO! (default: 42)
441
442
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300443prefix_chars
444^^^^^^^^^^^^
445
446Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
447Parsers that need to support different or additional prefix
448characters, e.g. for options
449like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
450to the ArgumentParser constructor::
451
452 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
453 >>> parser.add_argument('+f')
454 >>> parser.add_argument('++bar')
455 >>> parser.parse_args('+f X ++bar Y'.split())
456 Namespace(bar='Y', f='X')
457
458The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
459characters that does not include ``-`` will cause ``-f/--foo`` options to be
460disallowed.
461
462
463fromfile_prefix_chars
464^^^^^^^^^^^^^^^^^^^^^
465
466Sometimes, for example when dealing with a particularly long argument lists, it
467may make sense to keep the list of arguments in a file rather than typing it out
468at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
469:class:`ArgumentParser` constructor, then arguments that start with any of the
470specified characters will be treated as files, and will be replaced by the
471arguments they contain. For example::
472
473 >>> with open('args.txt', 'w') as fp:
Serhiy Storchaka12d547a2016-05-10 13:45:32 +0300474 ... fp.write('-f\nbar')
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300475 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
476 >>> parser.add_argument('-f')
477 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
478 Namespace(f='bar')
479
480Arguments read from a file must by default be one per line (but see also
481:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
482were in the same place as the original file referencing argument on the command
483line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
484is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
485
486The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
487arguments will never be treated as file references.
488
489
490argument_default
491^^^^^^^^^^^^^^^^
492
493Generally, argument defaults are specified either by passing a default to
494:meth:`~ArgumentParser.add_argument` or by calling the
495:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
496pairs. Sometimes however, it may be useful to specify a single parser-wide
497default for arguments. This can be accomplished by passing the
498``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
499to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
500calls, we supply ``argument_default=SUPPRESS``::
501
502 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
503 >>> parser.add_argument('--foo')
504 >>> parser.add_argument('bar', nargs='?')
505 >>> parser.parse_args(['--foo', '1', 'BAR'])
506 Namespace(bar='BAR', foo='1')
507 >>> parser.parse_args([])
508 Namespace()
509
510
Benjamin Petersona39e9662010-03-02 22:05:59 +0000511conflict_handler
512^^^^^^^^^^^^^^^^
513
Benjamin Peterson90c58022010-03-03 01:55:09 +0000514:class:`ArgumentParser` objects do not allow two actions with the same option
Martin Panterba5480b2016-09-08 05:39:59 +0000515string. By default, :class:`ArgumentParser` objects raise an exception if an
Benjamin Peterson90c58022010-03-03 01:55:09 +0000516attempt is made to create an argument with an option string that is already in
517use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000518
519 >>> parser = argparse.ArgumentParser(prog='PROG')
520 >>> parser.add_argument('-f', '--foo', help='old foo help')
521 >>> parser.add_argument('--foo', help='new foo help')
522 Traceback (most recent call last):
523 ..
524 ArgumentError: argument --foo: conflicting option string(s): --foo
525
526Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000527older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000528``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000529:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000530
531 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
532 >>> parser.add_argument('-f', '--foo', help='old foo help')
533 >>> parser.add_argument('--foo', help='new foo help')
534 >>> parser.print_help()
535 usage: PROG [-h] [-f FOO] [--foo FOO]
536
537 optional arguments:
538 -h, --help show this help message and exit
539 -f FOO old foo help
540 --foo FOO new foo help
541
Benjamin Peterson90c58022010-03-03 01:55:09 +0000542Note that :class:`ArgumentParser` objects only remove an action if all of its
543option strings are overridden. So, in the example above, the old ``-f/--foo``
544action is retained as the ``-f`` action, because only the ``--foo`` option
545string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000546
547
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300548add_help
549^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +0000550
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300551By default, ArgumentParser objects add an option which simply displays
552the parser's help message. For example, consider a file named
553``myprogram.py`` containing the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000554
555 import argparse
556 parser = argparse.ArgumentParser()
557 parser.add_argument('--foo', help='foo help')
558 args = parser.parse_args()
559
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300560If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Martin Panter8f1dd222016-07-26 11:18:21 +0200561help will be printed:
562
563.. code-block:: shell-session
Benjamin Petersona39e9662010-03-02 22:05:59 +0000564
565 $ python myprogram.py --help
566 usage: myprogram.py [-h] [--foo FOO]
567
568 optional arguments:
569 -h, --help show this help message and exit
570 --foo FOO foo help
Benjamin Petersona39e9662010-03-02 22:05:59 +0000571
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300572Occasionally, it may be useful to disable the addition of this help option.
573This can be achieved by passing ``False`` as the ``add_help=`` argument to
574:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000575
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300576 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
577 >>> parser.add_argument('--foo', help='foo help')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000578 >>> parser.print_help()
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300579 usage: PROG [--foo FOO]
Benjamin Petersona39e9662010-03-02 22:05:59 +0000580
581 optional arguments:
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300582 --foo FOO foo help
Benjamin Petersona39e9662010-03-02 22:05:59 +0000583
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300584The help option is typically ``-h/--help``. The exception to this is
585if the ``prefix_chars=`` is specified and does not include ``-``, in
586which case ``-h`` and ``--help`` are not valid options. In
587this case, the first character in ``prefix_chars`` is used to prefix
588the help options::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000589
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300590 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000591 >>> parser.print_help()
Georg Brandl2b385822013-10-06 09:50:36 +0200592 usage: PROG [+h]
Benjamin Petersona39e9662010-03-02 22:05:59 +0000593
594 optional arguments:
Georg Brandl2b385822013-10-06 09:50:36 +0200595 +h, ++help show this help message and exit
Benjamin Petersona39e9662010-03-02 22:05:59 +0000596
597
598The add_argument() method
599-------------------------
600
Éric Araujobb42f5e2012-02-20 02:08:01 +0100601.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
602 [const], [default], [type], [choices], [required], \
603 [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000604
Ezio Melotti12125822011-04-16 23:04:51 +0300605 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000606 has its own more detailed description below, but in short they are:
607
608 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300609 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000610
611 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300612 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000613
614 * nargs_ - The number of command-line arguments that should be consumed.
615
616 * const_ - A constant value required by some action_ and nargs_ selections.
617
618 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300619 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000620
Ezio Melotti12125822011-04-16 23:04:51 +0300621 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000622
623 * choices_ - A container of the allowable values for the argument.
624
625 * required_ - Whether or not the command-line option may be omitted
626 (optionals only).
627
628 * help_ - A brief description of what the argument does.
629
630 * metavar_ - A name for the argument in usage messages.
631
632 * dest_ - The name of the attribute to be added to the object returned by
633 :meth:`parse_args`.
634
Benjamin Peterson90c58022010-03-03 01:55:09 +0000635The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000636
Georg Brandlb8d0e362010-11-26 07:53:50 +0000637
Benjamin Petersona39e9662010-03-02 22:05:59 +0000638name or flags
639^^^^^^^^^^^^^
640
Ezio Melottic69313a2011-04-22 01:29:13 +0300641The :meth:`~ArgumentParser.add_argument` method must know whether an optional
642argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
643filenames, is expected. The first arguments passed to
644:meth:`~ArgumentParser.add_argument` must therefore be either a series of
645flags, or a simple argument name. For example, an optional argument could
646be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000647
648 >>> parser.add_argument('-f', '--foo')
649
650while a positional argument could be created like::
651
652 >>> parser.add_argument('bar')
653
Ezio Melottic69313a2011-04-22 01:29:13 +0300654When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
655identified by the ``-`` prefix, and the remaining arguments will be assumed to
656be positional::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000657
658 >>> parser = argparse.ArgumentParser(prog='PROG')
659 >>> parser.add_argument('-f', '--foo')
660 >>> parser.add_argument('bar')
661 >>> parser.parse_args(['BAR'])
662 Namespace(bar='BAR', foo=None)
663 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
664 Namespace(bar='BAR', foo='FOO')
665 >>> parser.parse_args(['--foo', 'FOO'])
666 usage: PROG [-h] [-f FOO] bar
667 PROG: error: too few arguments
668
Georg Brandlb8d0e362010-11-26 07:53:50 +0000669
Benjamin Petersona39e9662010-03-02 22:05:59 +0000670action
671^^^^^^
672
Éric Araujo67719bd2011-08-19 02:00:07 +0200673:class:`ArgumentParser` objects associate command-line arguments with actions. These
674actions can do just about anything with the command-line arguments associated with
Benjamin Petersona39e9662010-03-02 22:05:59 +0000675them, though most actions simply add an attribute to the object returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300676:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombs2c34fb52011-12-13 23:36:45 -0500677how the command-line arguments should be handled. The supplied actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000678
Georg Brandld2decd92010-03-02 22:17:38 +0000679* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300680 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000681
682 >>> parser = argparse.ArgumentParser()
683 >>> parser.add_argument('--foo')
684 >>> parser.parse_args('--foo 1'.split())
685 Namespace(foo='1')
686
687* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panter87d9de62016-04-09 03:49:48 +0000688 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti310619c2011-04-21 23:06:48 +0300689 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000690
691 >>> parser = argparse.ArgumentParser()
692 >>> parser.add_argument('--foo', action='store_const', const=42)
Martin Panter11cc5132016-04-26 11:33:46 +0000693 >>> parser.parse_args(['--foo'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000694 Namespace(foo=42)
695
Raymond Hettinger421467f2011-11-20 11:05:23 -0800696* ``'store_true'`` and ``'store_false'`` - These are special cases of
697 ``'store_const'`` using for storing the values ``True`` and ``False``
Serhiy Storchakae3d57872016-10-19 16:43:18 +0300698 respectively. In addition, they create default values of ``False`` and ``True``
Raymond Hettinger421467f2011-11-20 11:05:23 -0800699 respectively. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000700
701 >>> parser = argparse.ArgumentParser()
702 >>> parser.add_argument('--foo', action='store_true')
703 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettinger421467f2011-11-20 11:05:23 -0800704 >>> parser.add_argument('--baz', action='store_false')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000705 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettinger421467f2011-11-20 11:05:23 -0800706 Namespace(bar=False, baz=True, foo=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000707
708* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000709 list. This is useful to allow an option to be specified multiple times.
710 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000711
712 >>> parser = argparse.ArgumentParser()
713 >>> parser.add_argument('--foo', action='append')
714 >>> parser.parse_args('--foo 1 --foo 2'.split())
715 Namespace(foo=['1', '2'])
716
717* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000718 the const_ keyword argument to the list. (Note that the const_ keyword
719 argument defaults to ``None``.) The ``'append_const'`` action is typically
720 useful when multiple arguments need to store constants to the same list. For
721 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000722
723 >>> parser = argparse.ArgumentParser()
724 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
725 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
726 >>> parser.parse_args('--str --int'.split())
727 Namespace(types=[<type 'str'>, <type 'int'>])
728
Sandro Tosi8b211fc2012-01-04 23:24:48 +0100729* ``'count'`` - This counts the number of times a keyword argument occurs. For
730 example, this is useful for increasing verbosity levels::
731
732 >>> parser = argparse.ArgumentParser()
733 >>> parser.add_argument('--verbose', '-v', action='count')
Martin Panter11cc5132016-04-26 11:33:46 +0000734 >>> parser.parse_args(['-vvv'])
Sandro Tosi8b211fc2012-01-04 23:24:48 +0100735 Namespace(verbose=3)
736
737* ``'help'`` - This prints a complete help message for all the options in the
738 current parser and then exits. By default a help action is automatically
739 added to the parser. See :class:`ArgumentParser` for details of how the
740 output is created.
741
Benjamin Petersona39e9662010-03-02 22:05:59 +0000742* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melottic69313a2011-04-22 01:29:13 +0300743 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujobb42f5e2012-02-20 02:08:01 +0100744 and exits when invoked::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000745
746 >>> import argparse
747 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000748 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
749 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000750 PROG 2.0
751
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400752You may also specify an arbitrary action by passing an Action subclass or
753other object that implements the same interface. The recommended way to do
Jason R. Coombs2b492032014-08-03 14:54:11 -0400754this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400755and optionally the ``__init__`` method.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000756
Benjamin Peterson90c58022010-03-03 01:55:09 +0000757An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000758
759 >>> class FooAction(argparse.Action):
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400760 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
761 ... if nargs is not None:
762 ... raise ValueError("nargs not allowed")
763 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000764 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000765 ... print '%r %r %r' % (namespace, values, option_string)
766 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000767 ...
768 >>> parser = argparse.ArgumentParser()
769 >>> parser.add_argument('--foo', action=FooAction)
770 >>> parser.add_argument('bar', action=FooAction)
771 >>> args = parser.parse_args('1 --foo 2'.split())
772 Namespace(bar=None, foo=None) '1' None
773 Namespace(bar='1', foo=None) '2' '--foo'
774 >>> args
775 Namespace(bar='1', foo='2')
776
Jason R. Coombs2b492032014-08-03 14:54:11 -0400777For more details, see :class:`Action`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000778
779nargs
780^^^^^
781
782ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000783single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300784different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000785values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000786
Éric Araujobb42f5e2012-02-20 02:08:01 +0100787* ``N`` (an integer). ``N`` arguments from the command line will be gathered
788 together into a list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000789
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000790 >>> parser = argparse.ArgumentParser()
791 >>> parser.add_argument('--foo', nargs=2)
792 >>> parser.add_argument('bar', nargs=1)
793 >>> parser.parse_args('c --foo a b'.split())
794 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000795
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000796 Note that ``nargs=1`` produces a list of one item. This is different from
797 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000798
Éric Araujo67719bd2011-08-19 02:00:07 +0200799* ``'?'``. One argument will be consumed from the command line if possible, and
800 produced as a single item. If no command-line argument is present, the value from
Benjamin Petersona39e9662010-03-02 22:05:59 +0000801 default_ will be produced. Note that for optional arguments, there is an
802 additional case - the option string is present but not followed by a
Éric Araujo67719bd2011-08-19 02:00:07 +0200803 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Petersona39e9662010-03-02 22:05:59 +0000804 examples to illustrate this::
805
Georg Brandld2decd92010-03-02 22:17:38 +0000806 >>> parser = argparse.ArgumentParser()
807 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
808 >>> parser.add_argument('bar', nargs='?', default='d')
Martin Panter11cc5132016-04-26 11:33:46 +0000809 >>> parser.parse_args(['XX', '--foo', 'YY'])
Georg Brandld2decd92010-03-02 22:17:38 +0000810 Namespace(bar='XX', foo='YY')
Martin Panter11cc5132016-04-26 11:33:46 +0000811 >>> parser.parse_args(['XX', '--foo'])
Georg Brandld2decd92010-03-02 22:17:38 +0000812 Namespace(bar='XX', foo='c')
Martin Panter11cc5132016-04-26 11:33:46 +0000813 >>> parser.parse_args([])
Georg Brandld2decd92010-03-02 22:17:38 +0000814 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000815
Georg Brandld2decd92010-03-02 22:17:38 +0000816 One of the more common uses of ``nargs='?'`` is to allow optional input and
817 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000818
Georg Brandld2decd92010-03-02 22:17:38 +0000819 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000820 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
821 ... default=sys.stdin)
822 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
823 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000824 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000825 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
826 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000827 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000828 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
829 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000830
Éric Araujo67719bd2011-08-19 02:00:07 +0200831* ``'*'``. All command-line arguments present are gathered into a list. Note that
Georg Brandld2decd92010-03-02 22:17:38 +0000832 it generally doesn't make much sense to have more than one positional argument
833 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
834 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000835
Georg Brandld2decd92010-03-02 22:17:38 +0000836 >>> parser = argparse.ArgumentParser()
837 >>> parser.add_argument('--foo', nargs='*')
838 >>> parser.add_argument('--bar', nargs='*')
839 >>> parser.add_argument('baz', nargs='*')
840 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
841 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000842
843* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
844 list. Additionally, an error message will be generated if there wasn't at
Éric Araujo67719bd2011-08-19 02:00:07 +0200845 least one command-line argument present. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000846
Georg Brandld2decd92010-03-02 22:17:38 +0000847 >>> parser = argparse.ArgumentParser(prog='PROG')
848 >>> parser.add_argument('foo', nargs='+')
Martin Panter11cc5132016-04-26 11:33:46 +0000849 >>> parser.parse_args(['a', 'b'])
Georg Brandld2decd92010-03-02 22:17:38 +0000850 Namespace(foo=['a', 'b'])
Martin Panter11cc5132016-04-26 11:33:46 +0000851 >>> parser.parse_args([])
Georg Brandld2decd92010-03-02 22:17:38 +0000852 usage: PROG [-h] foo [foo ...]
853 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000854
Sandro Tosicb212272012-01-19 22:22:35 +0100855* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
856 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujobb42f5e2012-02-20 02:08:01 +0100857 to other command line utilities::
Sandro Tosi10f047d2012-01-19 21:59:34 +0100858
859 >>> parser = argparse.ArgumentParser(prog='PROG')
860 >>> parser.add_argument('--foo')
861 >>> parser.add_argument('command')
862 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosicb212272012-01-19 22:22:35 +0100863 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
864 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi10f047d2012-01-19 21:59:34 +0100865
Éric Araujo67719bd2011-08-19 02:00:07 +0200866If the ``nargs`` keyword argument is not provided, the number of arguments consumed
867is determined by the action_. Generally this means a single command-line argument
Benjamin Petersona39e9662010-03-02 22:05:59 +0000868will be consumed and a single item (not a list) will be produced.
869
870
871const
872^^^^^
873
Ezio Melottic69313a2011-04-22 01:29:13 +0300874The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
875constant values that are not read from the command line but are required for
876the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000877
Ezio Melottic69313a2011-04-22 01:29:13 +0300878* When :meth:`~ArgumentParser.add_argument` is called with
879 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujobb42f5e2012-02-20 02:08:01 +0100880 ``const`` value to one of the attributes of the object returned by
881 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000882
Ezio Melottic69313a2011-04-22 01:29:13 +0300883* When :meth:`~ArgumentParser.add_argument` is called with option strings
884 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujo67719bd2011-08-19 02:00:07 +0200885 argument that can be followed by zero or one command-line arguments.
Ezio Melottic69313a2011-04-22 01:29:13 +0300886 When parsing the command line, if the option string is encountered with no
Éric Araujo67719bd2011-08-19 02:00:07 +0200887 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melottic69313a2011-04-22 01:29:13 +0300888 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000889
Martin Panter87d9de62016-04-09 03:49:48 +0000890With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panterbf02d182016-04-16 09:28:57 +0000891keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000892
893
894default
895^^^^^^^
896
897All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300898command line. The ``default`` keyword argument of
899:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujo67719bd2011-08-19 02:00:07 +0200900specifies what value should be used if the command-line argument is not present.
Ezio Melottic69313a2011-04-22 01:29:13 +0300901For optional arguments, the ``default`` value is used when the option string
902was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000903
904 >>> parser = argparse.ArgumentParser()
905 >>> parser.add_argument('--foo', default=42)
Martin Panter11cc5132016-04-26 11:33:46 +0000906 >>> parser.parse_args(['--foo', '2'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000907 Namespace(foo='2')
Martin Panter11cc5132016-04-26 11:33:46 +0000908 >>> parser.parse_args([])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000909 Namespace(foo=42)
910
Barry Warsaw0dea9362012-09-25 10:32:53 -0400911If the ``default`` value is a string, the parser parses the value as if it
912were a command-line argument. In particular, the parser applies any type_
913conversion argument, if provided, before setting the attribute on the
914:class:`Namespace` return value. Otherwise, the parser uses the value as is::
915
916 >>> parser = argparse.ArgumentParser()
917 >>> parser.add_argument('--length', default='10', type=int)
918 >>> parser.add_argument('--width', default=10.5, type=int)
919 >>> parser.parse_args()
920 Namespace(length=10, width=10.5)
921
Éric Araujo67719bd2011-08-19 02:00:07 +0200922For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
923is used when no command-line argument was present::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000924
925 >>> parser = argparse.ArgumentParser()
926 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panter11cc5132016-04-26 11:33:46 +0000927 >>> parser.parse_args(['a'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000928 Namespace(foo='a')
Martin Panter11cc5132016-04-26 11:33:46 +0000929 >>> parser.parse_args([])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000930 Namespace(foo=42)
931
932
Benjamin Peterson90c58022010-03-03 01:55:09 +0000933Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
934command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000935
936 >>> parser = argparse.ArgumentParser()
937 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
938 >>> parser.parse_args([])
939 Namespace()
940 >>> parser.parse_args(['--foo', '1'])
941 Namespace(foo='1')
942
943
944type
945^^^^
946
Éric Araujo67719bd2011-08-19 02:00:07 +0200947By default, :class:`ArgumentParser` objects read command-line arguments in as simple
948strings. However, quite often the command-line string should instead be
949interpreted as another type, like a :class:`float` or :class:`int`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300950``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujo67719bd2011-08-19 02:00:07 +0200951necessary type-checking and type conversions to be performed. Common built-in
952types and functions can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000953
954 >>> parser = argparse.ArgumentParser()
955 >>> parser.add_argument('foo', type=int)
956 >>> parser.add_argument('bar', type=file)
957 >>> parser.parse_args('2 temp.txt'.split())
958 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
959
Barry Warsaw0dea9362012-09-25 10:32:53 -0400960See the section on the default_ keyword argument for information on when the
961``type`` argument is applied to default arguments.
962
Benjamin Petersona39e9662010-03-02 22:05:59 +0000963To ease the use of various types of files, the argparse module provides the
964factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000965``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000966writable file::
967
968 >>> parser = argparse.ArgumentParser()
969 >>> parser.add_argument('bar', type=argparse.FileType('w'))
970 >>> parser.parse_args(['out.txt'])
971 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
972
Benjamin Peterson90c58022010-03-03 01:55:09 +0000973``type=`` can take any callable that takes a single string argument and returns
Éric Araujo67719bd2011-08-19 02:00:07 +0200974the converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000975
976 >>> def perfect_square(string):
977 ... value = int(string)
978 ... sqrt = math.sqrt(value)
979 ... if sqrt != int(sqrt):
980 ... msg = "%r is not a perfect square" % string
981 ... raise argparse.ArgumentTypeError(msg)
982 ... return value
983 ...
984 >>> parser = argparse.ArgumentParser(prog='PROG')
985 >>> parser.add_argument('foo', type=perfect_square)
Martin Panter11cc5132016-04-26 11:33:46 +0000986 >>> parser.parse_args(['9'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000987 Namespace(foo=9)
Martin Panter11cc5132016-04-26 11:33:46 +0000988 >>> parser.parse_args(['7'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000989 usage: PROG [-h] foo
990 PROG: error: argument foo: '7' is not a perfect square
991
Benjamin Peterson90c58022010-03-03 01:55:09 +0000992The choices_ keyword argument may be more convenient for type checkers that
993simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000994
995 >>> parser = argparse.ArgumentParser(prog='PROG')
996 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
Martin Panter11cc5132016-04-26 11:33:46 +0000997 >>> parser.parse_args(['7'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000998 Namespace(foo=7)
Martin Panter11cc5132016-04-26 11:33:46 +0000999 >>> parser.parse_args(['11'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001000 usage: PROG [-h] {5,6,7,8,9}
1001 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1002
1003See the choices_ section for more details.
1004
1005
1006choices
1007^^^^^^^
1008
Éric Araujo67719bd2011-08-19 02:00:07 +02001009Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001010These can be handled by passing a container object as the *choices* keyword
Ezio Melottic69313a2011-04-22 01:29:13 +03001011argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001012parsed, argument values will be checked, and an error message will be displayed
1013if the argument was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001014
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001015 >>> parser = argparse.ArgumentParser(prog='game.py')
1016 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1017 >>> parser.parse_args(['rock'])
1018 Namespace(move='rock')
1019 >>> parser.parse_args(['fire'])
1020 usage: game.py [-h] {rock,paper,scissors}
1021 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1022 'paper', 'scissors')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001023
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001024Note that inclusion in the *choices* container is checked after any type_
1025conversions have been performed, so the type of the objects in the *choices*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001026container should match the type_ specified::
1027
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001028 >>> parser = argparse.ArgumentParser(prog='doors.py')
1029 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1030 >>> print(parser.parse_args(['3']))
1031 Namespace(door=3)
1032 >>> parser.parse_args(['4'])
1033 usage: doors.py [-h] {1,2,3}
1034 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001035
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001036Any object that supports the ``in`` operator can be passed as the *choices*
Georg Brandld2decd92010-03-02 22:17:38 +00001037value, so :class:`dict` objects, :class:`set` objects, custom containers,
1038etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001039
1040
1041required
1042^^^^^^^^
1043
Ezio Melotti01b600c2011-04-21 16:12:17 +03001044In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +03001045indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001046To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +03001047keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001048
1049 >>> parser = argparse.ArgumentParser()
1050 >>> parser.add_argument('--foo', required=True)
1051 >>> parser.parse_args(['--foo', 'BAR'])
1052 Namespace(foo='BAR')
1053 >>> parser.parse_args([])
1054 usage: argparse.py [-h] [--foo FOO]
1055 argparse.py: error: option --foo is required
1056
Ezio Melottic69313a2011-04-22 01:29:13 +03001057As the example shows, if an option is marked as ``required``,
1058:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1059present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001060
Benjamin Peterson90c58022010-03-03 01:55:09 +00001061.. note::
1062
1063 Required options are generally considered bad form because users expect
1064 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001065
1066
1067help
1068^^^^
1069
Benjamin Peterson90c58022010-03-03 01:55:09 +00001070The ``help`` value is a string containing a brief description of the argument.
1071When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001072command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001073argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001074
1075 >>> parser = argparse.ArgumentParser(prog='frobble')
1076 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001077 ... help='foo the bars before frobbling')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001078 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001079 ... help='one of the bars to be frobbled')
Martin Panter11cc5132016-04-26 11:33:46 +00001080 >>> parser.parse_args(['-h'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001081 usage: frobble [-h] [--foo] bar [bar ...]
1082
1083 positional arguments:
1084 bar one of the bars to be frobbled
1085
1086 optional arguments:
1087 -h, --help show this help message and exit
1088 --foo foo the bars before frobbling
1089
1090The ``help`` strings can include various format specifiers to avoid repetition
1091of things like the program name or the argument default_. The available
1092specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001093:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001094
1095 >>> parser = argparse.ArgumentParser(prog='frobble')
1096 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001097 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001098 >>> parser.print_help()
1099 usage: frobble [-h] [bar]
1100
1101 positional arguments:
1102 bar the bar to frobble (default: 42)
1103
1104 optional arguments:
1105 -h, --help show this help message and exit
1106
Sandro Tosi711f5472012-01-03 18:31:51 +01001107:mod:`argparse` supports silencing the help entry for certain options, by
1108setting the ``help`` value to ``argparse.SUPPRESS``::
1109
1110 >>> parser = argparse.ArgumentParser(prog='frobble')
1111 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1112 >>> parser.print_help()
1113 usage: frobble [-h]
1114
1115 optional arguments:
1116 -h, --help show this help message and exit
1117
Benjamin Petersona39e9662010-03-02 22:05:59 +00001118
1119metavar
1120^^^^^^^
1121
Sandro Tosi2534f9a2013-01-11 10:48:34 +01001122When :class:`ArgumentParser` generates help messages, it needs some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001123to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001124value as the "name" of each object. By default, for positional argument
1125actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001126the dest_ value is uppercased. So, a single positional argument with
Eli Benderskybba1dd52011-11-11 16:42:11 +02001127``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujo67719bd2011-08-19 02:00:07 +02001128optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson90c58022010-03-03 01:55:09 +00001129will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001130
1131 >>> parser = argparse.ArgumentParser()
1132 >>> parser.add_argument('--foo')
1133 >>> parser.add_argument('bar')
1134 >>> parser.parse_args('X --foo Y'.split())
1135 Namespace(bar='X', foo='Y')
1136 >>> parser.print_help()
1137 usage: [-h] [--foo FOO] bar
1138
1139 positional arguments:
1140 bar
1141
1142 optional arguments:
1143 -h, --help show this help message and exit
1144 --foo FOO
1145
Benjamin Peterson90c58022010-03-03 01:55:09 +00001146An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001147
1148 >>> parser = argparse.ArgumentParser()
1149 >>> parser.add_argument('--foo', metavar='YYY')
1150 >>> parser.add_argument('bar', metavar='XXX')
1151 >>> parser.parse_args('X --foo Y'.split())
1152 Namespace(bar='X', foo='Y')
1153 >>> parser.print_help()
1154 usage: [-h] [--foo YYY] XXX
1155
1156 positional arguments:
1157 XXX
1158
1159 optional arguments:
1160 -h, --help show this help message and exit
1161 --foo YYY
1162
1163Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001164attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1165by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001166
1167Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001168Providing a tuple to ``metavar`` specifies a different display for each of the
1169arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001170
1171 >>> parser = argparse.ArgumentParser(prog='PROG')
1172 >>> parser.add_argument('-x', nargs=2)
1173 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1174 >>> parser.print_help()
1175 usage: PROG [-h] [-x X X] [--foo bar baz]
1176
1177 optional arguments:
1178 -h, --help show this help message and exit
1179 -x X X
1180 --foo bar baz
1181
1182
1183dest
1184^^^^
1185
Benjamin Peterson90c58022010-03-03 01:55:09 +00001186Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001187object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1188attribute is determined by the ``dest`` keyword argument of
1189:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1190``dest`` is normally supplied as the first argument to
1191:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001192
1193 >>> parser = argparse.ArgumentParser()
1194 >>> parser.add_argument('bar')
Martin Panter11cc5132016-04-26 11:33:46 +00001195 >>> parser.parse_args(['XXX'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001196 Namespace(bar='XXX')
1197
1198For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001199the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo67719bd2011-08-19 02:00:07 +02001200taking the first long option string and stripping away the initial ``--``
Benjamin Petersona39e9662010-03-02 22:05:59 +00001201string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo67719bd2011-08-19 02:00:07 +02001202the first short option string by stripping the initial ``-`` character. Any
1203internal ``-`` characters will be converted to ``_`` characters to make sure
Georg Brandld2decd92010-03-02 22:17:38 +00001204the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001205behavior::
1206
1207 >>> parser = argparse.ArgumentParser()
1208 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1209 >>> parser.add_argument('-x', '-y')
1210 >>> parser.parse_args('-f 1 -x 2'.split())
1211 Namespace(foo_bar='1', x='2')
1212 >>> parser.parse_args('--foo 1 -y 2'.split())
1213 Namespace(foo_bar='1', x='2')
1214
Benjamin Peterson90c58022010-03-03 01:55:09 +00001215``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001216
1217 >>> parser = argparse.ArgumentParser()
1218 >>> parser.add_argument('--foo', dest='bar')
1219 >>> parser.parse_args('--foo XXX'.split())
1220 Namespace(bar='XXX')
1221
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001222Action classes
1223^^^^^^^^^^^^^^
1224
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001225Action classes implement the Action API, a callable which returns a callable
Benjamin Petersonceb0e1d2014-09-04 11:50:14 -04001226which processes arguments from the command-line. Any object which follows this
1227API may be passed as the ``action`` parameter to :meth:`add_argument`.
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001228
Berker Peksag80154582015-01-06 18:29:04 +02001229.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1230 type=None, choices=None, required=False, help=None, \
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001231 metavar=None)
1232
Benjamin Petersonceb0e1d2014-09-04 11:50:14 -04001233Action objects are used by an ArgumentParser to represent the information needed
1234to parse a single argument from one or more strings from the command line. The
1235Action class must accept the two positional arguments plus any keyword arguments
1236passed to :meth:`ArgumentParser.add_argument` except for the ``action`` itself.
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001237
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001238Instances of Action (or return value of any callable to the ``action``
1239parameter) should have attributes "dest", "option_strings", "default", "type",
1240"required", "help", etc. defined. The easiest way to ensure these attributes
1241are defined is to call ``Action.__init__``.
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001242
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001243Action instances should be callable, so subclasses must override the
1244``__call__`` method, which should accept four parameters:
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001245
1246* ``parser`` - The ArgumentParser object which contains this action.
1247
1248* ``namespace`` - The :class:`Namespace` object that will be returned by
1249 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1250 object using :func:`setattr`.
1251
1252* ``values`` - The associated command-line arguments, with any type conversions
1253 applied. Type conversions are specified with the type_ keyword argument to
1254 :meth:`~ArgumentParser.add_argument`.
1255
1256* ``option_string`` - The option string that was used to invoke this action.
1257 The ``option_string`` argument is optional, and will be absent if the action
1258 is associated with a positional argument.
1259
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001260The ``__call__`` method may perform arbitrary actions, but will typically set
1261attributes on the ``namespace`` based on ``dest`` and ``values``.
1262
Benjamin Petersona39e9662010-03-02 22:05:59 +00001263
1264The parse_args() method
1265-----------------------
1266
Georg Brandlb8d0e362010-11-26 07:53:50 +00001267.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001268
Benjamin Peterson90c58022010-03-03 01:55:09 +00001269 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001270 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001271
1272 Previous calls to :meth:`add_argument` determine exactly what objects are
1273 created and how they are assigned. See the documentation for
1274 :meth:`add_argument` for details.
1275
Éric Araujo67719bd2011-08-19 02:00:07 +02001276 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001277 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001278
Georg Brandlb8d0e362010-11-26 07:53:50 +00001279
Benjamin Petersona39e9662010-03-02 22:05:59 +00001280Option value syntax
1281^^^^^^^^^^^^^^^^^^^
1282
Ezio Melottic69313a2011-04-22 01:29:13 +03001283The :meth:`~ArgumentParser.parse_args` method supports several ways of
1284specifying the value of an option (if it takes one). In the simplest case, the
1285option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001286
1287 >>> parser = argparse.ArgumentParser(prog='PROG')
1288 >>> parser.add_argument('-x')
1289 >>> parser.add_argument('--foo')
Martin Panter11cc5132016-04-26 11:33:46 +00001290 >>> parser.parse_args(['-x', 'X'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001291 Namespace(foo=None, x='X')
Martin Panter11cc5132016-04-26 11:33:46 +00001292 >>> parser.parse_args(['--foo', 'FOO'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001293 Namespace(foo='FOO', x=None)
1294
Benjamin Peterson90c58022010-03-03 01:55:09 +00001295For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001296and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001297separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001298
Martin Panter11cc5132016-04-26 11:33:46 +00001299 >>> parser.parse_args(['--foo=FOO'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001300 Namespace(foo='FOO', x=None)
1301
Benjamin Peterson90c58022010-03-03 01:55:09 +00001302For short options (options only one character long), the option and its value
1303can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001304
Martin Panter11cc5132016-04-26 11:33:46 +00001305 >>> parser.parse_args(['-xX'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001306 Namespace(foo=None, x='X')
1307
Benjamin Peterson90c58022010-03-03 01:55:09 +00001308Several short options can be joined together, using only a single ``-`` prefix,
1309as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001310
1311 >>> parser = argparse.ArgumentParser(prog='PROG')
1312 >>> parser.add_argument('-x', action='store_true')
1313 >>> parser.add_argument('-y', action='store_true')
1314 >>> parser.add_argument('-z')
Martin Panter11cc5132016-04-26 11:33:46 +00001315 >>> parser.parse_args(['-xyzZ'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001316 Namespace(x=True, y=True, z='Z')
1317
1318
1319Invalid arguments
1320^^^^^^^^^^^^^^^^^
1321
Ezio Melottic69313a2011-04-22 01:29:13 +03001322While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1323variety of errors, including ambiguous options, invalid types, invalid options,
1324wrong number of positional arguments, etc. When it encounters such an error,
1325it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001326
1327 >>> parser = argparse.ArgumentParser(prog='PROG')
1328 >>> parser.add_argument('--foo', type=int)
1329 >>> parser.add_argument('bar', nargs='?')
1330
1331 >>> # invalid type
1332 >>> parser.parse_args(['--foo', 'spam'])
1333 usage: PROG [-h] [--foo FOO] [bar]
1334 PROG: error: argument --foo: invalid int value: 'spam'
1335
1336 >>> # invalid option
1337 >>> parser.parse_args(['--bar'])
1338 usage: PROG [-h] [--foo FOO] [bar]
1339 PROG: error: no such option: --bar
1340
1341 >>> # wrong number of arguments
1342 >>> parser.parse_args(['spam', 'badger'])
1343 usage: PROG [-h] [--foo FOO] [bar]
1344 PROG: error: extra arguments found: badger
1345
1346
Éric Araujo67719bd2011-08-19 02:00:07 +02001347Arguments containing ``-``
1348^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001349
Ezio Melottic69313a2011-04-22 01:29:13 +03001350The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1351the user has clearly made a mistake, but some situations are inherently
Éric Araujo67719bd2011-08-19 02:00:07 +02001352ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melottic69313a2011-04-22 01:29:13 +03001353attempt to specify an option or an attempt to provide a positional argument.
1354The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo67719bd2011-08-19 02:00:07 +02001355arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melottic69313a2011-04-22 01:29:13 +03001356there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001357
1358 >>> parser = argparse.ArgumentParser(prog='PROG')
1359 >>> parser.add_argument('-x')
1360 >>> parser.add_argument('foo', nargs='?')
1361
1362 >>> # no negative number options, so -1 is a positional argument
1363 >>> parser.parse_args(['-x', '-1'])
1364 Namespace(foo=None, x='-1')
1365
1366 >>> # no negative number options, so -1 and -5 are positional arguments
1367 >>> parser.parse_args(['-x', '-1', '-5'])
1368 Namespace(foo='-5', x='-1')
1369
1370 >>> parser = argparse.ArgumentParser(prog='PROG')
1371 >>> parser.add_argument('-1', dest='one')
1372 >>> parser.add_argument('foo', nargs='?')
1373
1374 >>> # negative number options present, so -1 is an option
1375 >>> parser.parse_args(['-1', 'X'])
1376 Namespace(foo=None, one='X')
1377
1378 >>> # negative number options present, so -2 is an option
1379 >>> parser.parse_args(['-2'])
1380 usage: PROG [-h] [-1 ONE] [foo]
1381 PROG: error: no such option: -2
1382
1383 >>> # negative number options present, so both -1s are options
1384 >>> parser.parse_args(['-1', '-1'])
1385 usage: PROG [-h] [-1 ONE] [foo]
1386 PROG: error: argument -1: expected one argument
1387
Éric Araujo67719bd2011-08-19 02:00:07 +02001388If you have positional arguments that must begin with ``-`` and don't look
Benjamin Petersona39e9662010-03-02 22:05:59 +00001389like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001390:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1391argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001392
1393 >>> parser.parse_args(['--', '-f'])
1394 Namespace(foo='-f', one=None)
1395
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001396.. _prefix-matching:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001397
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001398Argument abbreviations (prefix matching)
1399^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001400
Ezio Melottic69313a2011-04-22 01:29:13 +03001401The :meth:`~ArgumentParser.parse_args` method allows long options to be
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001402abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
1403a unique option)::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001404
1405 >>> parser = argparse.ArgumentParser(prog='PROG')
1406 >>> parser.add_argument('-bacon')
1407 >>> parser.add_argument('-badger')
1408 >>> parser.parse_args('-bac MMM'.split())
1409 Namespace(bacon='MMM', badger=None)
1410 >>> parser.parse_args('-bad WOOD'.split())
1411 Namespace(bacon=None, badger='WOOD')
1412 >>> parser.parse_args('-ba BA'.split())
1413 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1414 PROG: error: ambiguous option: -ba could match -badger, -bacon
1415
Benjamin Peterson90c58022010-03-03 01:55:09 +00001416An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001417
1418
1419Beyond ``sys.argv``
1420^^^^^^^^^^^^^^^^^^^
1421
Éric Araujo67719bd2011-08-19 02:00:07 +02001422Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Georg Brandld2decd92010-03-02 22:17:38 +00001423of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001424:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1425interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001426
1427 >>> parser = argparse.ArgumentParser()
1428 >>> parser.add_argument(
1429 ... 'integers', metavar='int', type=int, choices=xrange(10),
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001430 ... nargs='+', help='an integer in the range 0..9')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001431 >>> parser.add_argument(
1432 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001433 ... default=max, help='sum the integers (default: find the max)')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001434 >>> parser.parse_args(['1', '2', '3', '4'])
1435 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panter11cc5132016-04-26 11:33:46 +00001436 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001437 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1438
1439
Steven Bethard3f69a052011-03-26 19:59:02 +01001440The Namespace object
1441^^^^^^^^^^^^^^^^^^^^
1442
Éric Araujof0d44bc2011-07-29 17:59:17 +02001443.. class:: Namespace
1444
1445 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1446 an object holding attributes and return it.
1447
1448This class is deliberately simple, just an :class:`object` subclass with a
1449readable string representation. If you prefer to have dict-like view of the
1450attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001451
1452 >>> parser = argparse.ArgumentParser()
1453 >>> parser.add_argument('--foo')
1454 >>> args = parser.parse_args(['--foo', 'BAR'])
1455 >>> vars(args)
1456 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001457
Benjamin Peterson90c58022010-03-03 01:55:09 +00001458It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001459already existing object, rather than a new :class:`Namespace` object. This can
1460be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001461
1462 >>> class C(object):
1463 ... pass
1464 ...
1465 >>> c = C()
1466 >>> parser = argparse.ArgumentParser()
1467 >>> parser.add_argument('--foo')
1468 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1469 >>> c.foo
1470 'BAR'
1471
1472
1473Other utilities
1474---------------
1475
1476Sub-commands
1477^^^^^^^^^^^^
1478
Georg Brandl1f94b262013-10-06 18:51:39 +02001479.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1480 [parser_class], [action], \
1481 [option_string], [dest], [help], \
1482 [metavar])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001483
Benjamin Peterson90c58022010-03-03 01:55:09 +00001484 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001485 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001486 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001487 this way can be a particularly good idea when a program performs several
1488 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001489 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001490 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti82ee3032012-12-28 01:59:24 +02001491 called with no arguments and returns a special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001492 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1493 command name and any :class:`ArgumentParser` constructor arguments, and
1494 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001495
Georg Brandl1f94b262013-10-06 18:51:39 +02001496 Description of parameters:
1497
1498 * title - title for the sub-parser group in help output; by default
1499 "subcommands" if description is provided, otherwise uses title for
1500 positional arguments
1501
1502 * description - description for the sub-parser group in help output, by
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001503 default ``None``
Georg Brandl1f94b262013-10-06 18:51:39 +02001504
1505 * prog - usage information that will be displayed with sub-command help,
1506 by default the name of the program and any positional arguments before the
1507 subparser argument
1508
1509 * parser_class - class which will be used to create sub-parser instances, by
1510 default the class of the current parser (e.g. ArgumentParser)
1511
Berker Peksag1b6e5382015-01-20 06:55:51 +02001512 * action_ - the basic type of action to be taken when this argument is
1513 encountered at the command line
1514
1515 * dest_ - name of the attribute under which sub-command name will be
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001516 stored; by default ``None`` and no value is stored
Georg Brandl1f94b262013-10-06 18:51:39 +02001517
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001518 * help_ - help for sub-parser group in help output, by default ``None``
Georg Brandl1f94b262013-10-06 18:51:39 +02001519
Berker Peksag1b6e5382015-01-20 06:55:51 +02001520 * metavar_ - string presenting available sub-commands in help; by default it
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001521 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
Georg Brandl1f94b262013-10-06 18:51:39 +02001522
Benjamin Petersona39e9662010-03-02 22:05:59 +00001523 Some example usage::
1524
1525 >>> # create the top-level parser
1526 >>> parser = argparse.ArgumentParser(prog='PROG')
1527 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1528 >>> subparsers = parser.add_subparsers(help='sub-command help')
1529 >>>
1530 >>> # create the parser for the "a" command
1531 >>> parser_a = subparsers.add_parser('a', help='a help')
1532 >>> parser_a.add_argument('bar', type=int, help='bar help')
1533 >>>
1534 >>> # create the parser for the "b" command
1535 >>> parser_b = subparsers.add_parser('b', help='b help')
1536 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1537 >>>
Éric Araujo67719bd2011-08-19 02:00:07 +02001538 >>> # parse some argument lists
Benjamin Petersona39e9662010-03-02 22:05:59 +00001539 >>> parser.parse_args(['a', '12'])
1540 Namespace(bar=12, foo=False)
1541 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1542 Namespace(baz='Z', foo=True)
1543
1544 Note that the object returned by :meth:`parse_args` will only contain
1545 attributes for the main parser and the subparser that was selected by the
1546 command line (and not any other subparsers). So in the example above, when
Éric Araujo67719bd2011-08-19 02:00:07 +02001547 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1548 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001549 ``baz`` attributes are present.
1550
1551 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001552 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001553 include parent parser or sibling parser messages. (A help message for each
1554 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001555 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001556
1557 ::
1558
1559 >>> parser.parse_args(['--help'])
1560 usage: PROG [-h] [--foo] {a,b} ...
1561
1562 positional arguments:
1563 {a,b} sub-command help
Ezio Melottidc157fc2013-01-12 10:39:45 +02001564 a a help
1565 b b help
Benjamin Petersona39e9662010-03-02 22:05:59 +00001566
1567 optional arguments:
1568 -h, --help show this help message and exit
1569 --foo foo help
1570
1571 >>> parser.parse_args(['a', '--help'])
1572 usage: PROG a [-h] bar
1573
1574 positional arguments:
1575 bar bar help
1576
1577 optional arguments:
1578 -h, --help show this help message and exit
1579
1580 >>> parser.parse_args(['b', '--help'])
1581 usage: PROG b [-h] [--baz {X,Y,Z}]
1582
1583 optional arguments:
1584 -h, --help show this help message and exit
1585 --baz {X,Y,Z} baz help
1586
Georg Brandld2decd92010-03-02 22:17:38 +00001587 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1588 keyword arguments. When either is present, the subparser's commands will
1589 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001590
1591 >>> parser = argparse.ArgumentParser()
1592 >>> subparsers = parser.add_subparsers(title='subcommands',
1593 ... description='valid subcommands',
1594 ... help='additional help')
1595 >>> subparsers.add_parser('foo')
1596 >>> subparsers.add_parser('bar')
1597 >>> parser.parse_args(['-h'])
1598 usage: [-h] {foo,bar} ...
1599
1600 optional arguments:
1601 -h, --help show this help message and exit
1602
1603 subcommands:
1604 valid subcommands
1605
1606 {foo,bar} additional help
1607
1608
Georg Brandld2decd92010-03-02 22:17:38 +00001609 One particularly effective way of handling sub-commands is to combine the use
1610 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1611 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001612 example::
1613
1614 >>> # sub-command functions
1615 >>> def foo(args):
1616 ... print args.x * args.y
1617 ...
1618 >>> def bar(args):
1619 ... print '((%s))' % args.z
1620 ...
1621 >>> # create the top-level parser
1622 >>> parser = argparse.ArgumentParser()
1623 >>> subparsers = parser.add_subparsers()
1624 >>>
1625 >>> # create the parser for the "foo" command
1626 >>> parser_foo = subparsers.add_parser('foo')
1627 >>> parser_foo.add_argument('-x', type=int, default=1)
1628 >>> parser_foo.add_argument('y', type=float)
1629 >>> parser_foo.set_defaults(func=foo)
1630 >>>
1631 >>> # create the parser for the "bar" command
1632 >>> parser_bar = subparsers.add_parser('bar')
1633 >>> parser_bar.add_argument('z')
1634 >>> parser_bar.set_defaults(func=bar)
1635 >>>
1636 >>> # parse the args and call whatever function was selected
1637 >>> args = parser.parse_args('foo 1 -x 2'.split())
1638 >>> args.func(args)
1639 2.0
1640 >>>
1641 >>> # parse the args and call whatever function was selected
1642 >>> args = parser.parse_args('bar XYZYX'.split())
1643 >>> args.func(args)
1644 ((XYZYX))
1645
Éric Araujobb42f5e2012-02-20 02:08:01 +01001646 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson90c58022010-03-03 01:55:09 +00001647 appropriate function after argument parsing is complete. Associating
1648 functions with actions like this is typically the easiest way to handle the
1649 different actions for each of your subparsers. However, if it is necessary
1650 to check the name of the subparser that was invoked, the ``dest`` keyword
1651 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001652
1653 >>> parser = argparse.ArgumentParser()
1654 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1655 >>> subparser1 = subparsers.add_parser('1')
1656 >>> subparser1.add_argument('-x')
1657 >>> subparser2 = subparsers.add_parser('2')
1658 >>> subparser2.add_argument('y')
1659 >>> parser.parse_args(['2', 'frobble'])
1660 Namespace(subparser_name='2', y='frobble')
1661
1662
1663FileType objects
1664^^^^^^^^^^^^^^^^
1665
1666.. class:: FileType(mode='r', bufsize=None)
1667
1668 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001669 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujo67719bd2011-08-19 02:00:07 +02001670 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujobb42f5e2012-02-20 02:08:01 +01001671 with the requested modes and buffer sizes::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001672
Éric Araujobb42f5e2012-02-20 02:08:01 +01001673 >>> parser = argparse.ArgumentParser()
1674 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1675 >>> parser.parse_args(['--output', 'out'])
1676 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001677
1678 FileType objects understand the pseudo-argument ``'-'`` and automatically
1679 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujobb42f5e2012-02-20 02:08:01 +01001680 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001681
Éric Araujobb42f5e2012-02-20 02:08:01 +01001682 >>> parser = argparse.ArgumentParser()
1683 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1684 >>> parser.parse_args(['-'])
1685 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001686
1687
1688Argument groups
1689^^^^^^^^^^^^^^^
1690
Georg Brandlb8d0e362010-11-26 07:53:50 +00001691.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001692
Benjamin Peterson90c58022010-03-03 01:55:09 +00001693 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001694 "positional arguments" and "optional arguments" when displaying help
1695 messages. When there is a better conceptual grouping of arguments than this
1696 default one, appropriate groups can be created using the
1697 :meth:`add_argument_group` method::
1698
1699 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1700 >>> group = parser.add_argument_group('group')
1701 >>> group.add_argument('--foo', help='foo help')
1702 >>> group.add_argument('bar', help='bar help')
1703 >>> parser.print_help()
1704 usage: PROG [--foo FOO] bar
1705
1706 group:
1707 bar bar help
1708 --foo FOO foo help
1709
1710 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001711 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1712 :class:`ArgumentParser`. When an argument is added to the group, the parser
1713 treats it just like a normal argument, but displays the argument in a
1714 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001715 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001716 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001717
1718 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1719 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1720 >>> group1.add_argument('foo', help='foo help')
1721 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1722 >>> group2.add_argument('--bar', help='bar help')
1723 >>> parser.print_help()
1724 usage: PROG [--bar BAR] foo
1725
1726 group1:
1727 group1 description
1728
1729 foo foo help
1730
1731 group2:
1732 group2 description
1733
1734 --bar BAR bar help
1735
Sandro Tosi48a88952012-03-26 19:35:52 +02001736 Note that any arguments not in your user-defined groups will end up back
1737 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001738
1739
1740Mutual exclusion
1741^^^^^^^^^^^^^^^^
1742
Georg Brandle3005462013-10-06 13:09:59 +02001743.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001744
Ezio Melotti01b600c2011-04-21 16:12:17 +03001745 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1746 one of the arguments in the mutually exclusive group was present on the
1747 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001748
1749 >>> parser = argparse.ArgumentParser(prog='PROG')
1750 >>> group = parser.add_mutually_exclusive_group()
1751 >>> group.add_argument('--foo', action='store_true')
1752 >>> group.add_argument('--bar', action='store_false')
1753 >>> parser.parse_args(['--foo'])
1754 Namespace(bar=True, foo=True)
1755 >>> parser.parse_args(['--bar'])
1756 Namespace(bar=False, foo=False)
1757 >>> parser.parse_args(['--foo', '--bar'])
1758 usage: PROG [-h] [--foo | --bar]
1759 PROG: error: argument --bar: not allowed with argument --foo
1760
Georg Brandlb8d0e362010-11-26 07:53:50 +00001761 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001762 argument, to indicate that at least one of the mutually exclusive arguments
1763 is required::
1764
1765 >>> parser = argparse.ArgumentParser(prog='PROG')
1766 >>> group = parser.add_mutually_exclusive_group(required=True)
1767 >>> group.add_argument('--foo', action='store_true')
1768 >>> group.add_argument('--bar', action='store_false')
1769 >>> parser.parse_args([])
1770 usage: PROG [-h] (--foo | --bar)
1771 PROG: error: one of the arguments --foo --bar is required
1772
1773 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001774 *title* and *description* arguments of
1775 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001776
1777
1778Parser defaults
1779^^^^^^^^^^^^^^^
1780
Benjamin Peterson90c58022010-03-03 01:55:09 +00001781.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001782
Georg Brandld2decd92010-03-02 22:17:38 +00001783 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujo67719bd2011-08-19 02:00:07 +02001784 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001785 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001786 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001787 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001788
1789 >>> parser = argparse.ArgumentParser()
1790 >>> parser.add_argument('foo', type=int)
1791 >>> parser.set_defaults(bar=42, baz='badger')
1792 >>> parser.parse_args(['736'])
1793 Namespace(bar=42, baz='badger', foo=736)
1794
Benjamin Peterson90c58022010-03-03 01:55:09 +00001795 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001796
1797 >>> parser = argparse.ArgumentParser()
1798 >>> parser.add_argument('--foo', default='bar')
1799 >>> parser.set_defaults(foo='spam')
1800 >>> parser.parse_args([])
1801 Namespace(foo='spam')
1802
Benjamin Peterson90c58022010-03-03 01:55:09 +00001803 Parser-level defaults can be particularly useful when working with multiple
1804 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1805 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001806
Benjamin Peterson90c58022010-03-03 01:55:09 +00001807.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001808
1809 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001810 :meth:`~ArgumentParser.add_argument` or by
1811 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001812
1813 >>> parser = argparse.ArgumentParser()
1814 >>> parser.add_argument('--foo', default='badger')
1815 >>> parser.get_default('foo')
1816 'badger'
1817
1818
1819Printing help
1820^^^^^^^^^^^^^
1821
Ezio Melottic69313a2011-04-22 01:29:13 +03001822In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1823care of formatting and printing any usage or error messages. However, several
1824formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001825
Georg Brandlb8d0e362010-11-26 07:53:50 +00001826.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001827
1828 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001829 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001830 assumed.
1831
Georg Brandlb8d0e362010-11-26 07:53:50 +00001832.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001833
1834 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001835 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001836 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001837
1838There are also variants of these methods that simply return a string instead of
1839printing it:
1840
Georg Brandlb8d0e362010-11-26 07:53:50 +00001841.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001842
1843 Return a string containing a brief description of how the
1844 :class:`ArgumentParser` should be invoked on the command line.
1845
Georg Brandlb8d0e362010-11-26 07:53:50 +00001846.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001847
1848 Return a string containing a help message, including the program usage and
1849 information about the arguments registered with the :class:`ArgumentParser`.
1850
1851
Benjamin Petersona39e9662010-03-02 22:05:59 +00001852Partial parsing
1853^^^^^^^^^^^^^^^
1854
Georg Brandlb8d0e362010-11-26 07:53:50 +00001855.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001856
Ezio Melotti12125822011-04-16 23:04:51 +03001857Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001858the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001859:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001860:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1861extra arguments are present. Instead, it returns a two item tuple containing
1862the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001863
1864::
1865
1866 >>> parser = argparse.ArgumentParser()
1867 >>> parser.add_argument('--foo', action='store_true')
1868 >>> parser.add_argument('bar')
1869 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1870 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1871
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001872.. warning::
1873 :ref:`Prefix matching <prefix-matching>` rules apply to
1874 :meth:`parse_known_args`. The parser may consume an option even if it's just
1875 a prefix of one of its known options, instead of leaving it in the remaining
1876 arguments list.
1877
Benjamin Petersona39e9662010-03-02 22:05:59 +00001878
1879Customizing file parsing
1880^^^^^^^^^^^^^^^^^^^^^^^^
1881
Benjamin Peterson90c58022010-03-03 01:55:09 +00001882.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001883
Georg Brandlb8d0e362010-11-26 07:53:50 +00001884 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001885 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft5db0b332014-05-20 12:58:38 -04001886 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson90c58022010-03-03 01:55:09 +00001887 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001888
Georg Brandlb8d0e362010-11-26 07:53:50 +00001889 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001890 the argument file. It returns a list of arguments parsed from this string.
1891 The method is called once per line read from the argument file, in order.
1892
Georg Brandld2decd92010-03-02 22:17:38 +00001893 A useful override of this method is one that treats each space-separated word
1894 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001895
1896 def convert_arg_line_to_args(self, arg_line):
Berker Peksag31200ff2015-04-26 12:12:45 +03001897 return arg_line.split()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001898
1899
Georg Brandlb8d0e362010-11-26 07:53:50 +00001900Exiting methods
1901^^^^^^^^^^^^^^^
1902
1903.. method:: ArgumentParser.exit(status=0, message=None)
1904
1905 This method terminates the program, exiting with the specified *status*
1906 and, if given, it prints a *message* before that.
1907
1908.. method:: ArgumentParser.error(message)
1909
1910 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001911 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001912
1913
Georg Brandl58df6792010-07-03 10:25:47 +00001914.. _argparse-from-optparse:
1915
Benjamin Petersona39e9662010-03-02 22:05:59 +00001916Upgrading optparse code
1917-----------------------
1918
Ezio Melottic69313a2011-04-22 01:29:13 +03001919Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001920with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1921transparently, particularly with the changes required to support the new
1922``nargs=`` specifiers and better usage messages. When most everything in
1923:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1924longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001925
Berker Peksag12f05322014-09-26 15:39:05 +03001926The :mod:`argparse` module improves on the standard library :mod:`optparse`
1927module in a number of ways including:
1928
1929* Handling positional arguments.
1930* Supporting sub-commands.
1931* Allowing alternative option prefixes like ``+`` and ``/``.
1932* Handling zero-or-more and one-or-more style arguments.
1933* Producing more informative usage messages.
1934* Providing a much simpler interface for custom ``type`` and ``action``.
1935
Ezio Melotti01b600c2011-04-21 16:12:17 +03001936A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001937
Ezio Melottic69313a2011-04-22 01:29:13 +03001938* Replace all :meth:`optparse.OptionParser.add_option` calls with
1939 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001940
R David Murray5080cad2012-03-30 18:09:07 -04001941* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001942 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5080cad2012-03-30 18:09:07 -04001943 calls for the positional arguments. Keep in mind that what was previously
1944 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001945
1946* Replace callback actions and the ``callback_*`` keyword arguments with
1947 ``type`` or ``action`` arguments.
1948
1949* Replace string names for ``type`` keyword arguments with the corresponding
1950 type objects (e.g. int, float, complex, etc).
1951
Benjamin Peterson90c58022010-03-03 01:55:09 +00001952* Replace :class:`optparse.Values` with :class:`Namespace` and
1953 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1954 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001955
Georg Brandld2decd92010-03-02 22:17:38 +00001956* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001957 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001958 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001959
1960* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panter4ed35fc2015-10-10 10:52:35 +00001961 ``parser.add_argument('--version', action='version', version='<the version>')``.