blob: 799336092a9edb8ae9c7ceb1fe300d58e0b6418d [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,
Miss Islington (bot)82cae7c2017-09-07 14:17:42 -0700422including argument descriptions. However, multiple new lines are replaced with
423one. If you wish to preserve multiple blank lines, add spaces between the
424newlines.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000425
Benjamin Peterson90c58022010-03-03 01:55:09 +0000426The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000427will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000428
429 >>> parser = argparse.ArgumentParser(
430 ... prog='PROG',
431 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
432 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
433 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
434 >>> parser.print_help()
435 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
436
437 positional arguments:
438 bar BAR! (default: [1, 2, 3])
439
440 optional arguments:
441 -h, --help show this help message and exit
442 --foo FOO FOO! (default: 42)
443
444
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300445prefix_chars
446^^^^^^^^^^^^
447
448Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
449Parsers that need to support different or additional prefix
450characters, e.g. for options
451like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
452to the ArgumentParser constructor::
453
454 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
455 >>> parser.add_argument('+f')
456 >>> parser.add_argument('++bar')
457 >>> parser.parse_args('+f X ++bar Y'.split())
458 Namespace(bar='Y', f='X')
459
460The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
461characters that does not include ``-`` will cause ``-f/--foo`` options to be
462disallowed.
463
464
465fromfile_prefix_chars
466^^^^^^^^^^^^^^^^^^^^^
467
468Sometimes, for example when dealing with a particularly long argument lists, it
469may make sense to keep the list of arguments in a file rather than typing it out
470at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
471:class:`ArgumentParser` constructor, then arguments that start with any of the
472specified characters will be treated as files, and will be replaced by the
473arguments they contain. For example::
474
475 >>> with open('args.txt', 'w') as fp:
Serhiy Storchaka12d547a2016-05-10 13:45:32 +0300476 ... fp.write('-f\nbar')
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300477 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
478 >>> parser.add_argument('-f')
479 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
480 Namespace(f='bar')
481
482Arguments read from a file must by default be one per line (but see also
483:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
484were in the same place as the original file referencing argument on the command
485line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
486is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
487
488The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
489arguments will never be treated as file references.
490
491
492argument_default
493^^^^^^^^^^^^^^^^
494
495Generally, argument defaults are specified either by passing a default to
496:meth:`~ArgumentParser.add_argument` or by calling the
497:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
498pairs. Sometimes however, it may be useful to specify a single parser-wide
499default for arguments. This can be accomplished by passing the
500``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
501to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
502calls, we supply ``argument_default=SUPPRESS``::
503
504 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
505 >>> parser.add_argument('--foo')
506 >>> parser.add_argument('bar', nargs='?')
507 >>> parser.parse_args(['--foo', '1', 'BAR'])
508 Namespace(bar='BAR', foo='1')
509 >>> parser.parse_args([])
510 Namespace()
511
512
Benjamin Petersona39e9662010-03-02 22:05:59 +0000513conflict_handler
514^^^^^^^^^^^^^^^^
515
Benjamin Peterson90c58022010-03-03 01:55:09 +0000516:class:`ArgumentParser` objects do not allow two actions with the same option
Martin Panterba5480b2016-09-08 05:39:59 +0000517string. By default, :class:`ArgumentParser` objects raise an exception if an
Benjamin Peterson90c58022010-03-03 01:55:09 +0000518attempt is made to create an argument with an option string that is already in
519use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000520
521 >>> parser = argparse.ArgumentParser(prog='PROG')
522 >>> parser.add_argument('-f', '--foo', help='old foo help')
523 >>> parser.add_argument('--foo', help='new foo help')
524 Traceback (most recent call last):
525 ..
526 ArgumentError: argument --foo: conflicting option string(s): --foo
527
528Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000529older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000530``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000531:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000532
533 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
534 >>> parser.add_argument('-f', '--foo', help='old foo help')
535 >>> parser.add_argument('--foo', help='new foo help')
536 >>> parser.print_help()
537 usage: PROG [-h] [-f FOO] [--foo FOO]
538
539 optional arguments:
540 -h, --help show this help message and exit
541 -f FOO old foo help
542 --foo FOO new foo help
543
Benjamin Peterson90c58022010-03-03 01:55:09 +0000544Note that :class:`ArgumentParser` objects only remove an action if all of its
545option strings are overridden. So, in the example above, the old ``-f/--foo``
546action is retained as the ``-f`` action, because only the ``--foo`` option
547string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000548
549
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300550add_help
551^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +0000552
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300553By default, ArgumentParser objects add an option which simply displays
554the parser's help message. For example, consider a file named
555``myprogram.py`` containing the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000556
557 import argparse
558 parser = argparse.ArgumentParser()
559 parser.add_argument('--foo', help='foo help')
560 args = parser.parse_args()
561
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300562If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Martin Panter8f1dd222016-07-26 11:18:21 +0200563help will be printed:
564
565.. code-block:: shell-session
Benjamin Petersona39e9662010-03-02 22:05:59 +0000566
567 $ python myprogram.py --help
568 usage: myprogram.py [-h] [--foo FOO]
569
570 optional arguments:
571 -h, --help show this help message and exit
572 --foo FOO foo help
Benjamin Petersona39e9662010-03-02 22:05:59 +0000573
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300574Occasionally, it may be useful to disable the addition of this help option.
575This can be achieved by passing ``False`` as the ``add_help=`` argument to
576:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000577
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300578 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
579 >>> parser.add_argument('--foo', help='foo help')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000580 >>> parser.print_help()
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300581 usage: PROG [--foo FOO]
Benjamin Petersona39e9662010-03-02 22:05:59 +0000582
583 optional arguments:
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300584 --foo FOO foo help
Benjamin Petersona39e9662010-03-02 22:05:59 +0000585
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300586The help option is typically ``-h/--help``. The exception to this is
587if the ``prefix_chars=`` is specified and does not include ``-``, in
588which case ``-h`` and ``--help`` are not valid options. In
589this case, the first character in ``prefix_chars`` is used to prefix
590the help options::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000591
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300592 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000593 >>> parser.print_help()
Georg Brandl2b385822013-10-06 09:50:36 +0200594 usage: PROG [+h]
Benjamin Petersona39e9662010-03-02 22:05:59 +0000595
596 optional arguments:
Georg Brandl2b385822013-10-06 09:50:36 +0200597 +h, ++help show this help message and exit
Benjamin Petersona39e9662010-03-02 22:05:59 +0000598
599
600The add_argument() method
601-------------------------
602
Éric Araujobb42f5e2012-02-20 02:08:01 +0100603.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
604 [const], [default], [type], [choices], [required], \
605 [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000606
Ezio Melotti12125822011-04-16 23:04:51 +0300607 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000608 has its own more detailed description below, but in short they are:
609
610 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300611 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000612
613 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300614 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000615
616 * nargs_ - The number of command-line arguments that should be consumed.
617
618 * const_ - A constant value required by some action_ and nargs_ selections.
619
620 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300621 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000622
Ezio Melotti12125822011-04-16 23:04:51 +0300623 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000624
625 * choices_ - A container of the allowable values for the argument.
626
627 * required_ - Whether or not the command-line option may be omitted
628 (optionals only).
629
630 * help_ - A brief description of what the argument does.
631
632 * metavar_ - A name for the argument in usage messages.
633
634 * dest_ - The name of the attribute to be added to the object returned by
635 :meth:`parse_args`.
636
Benjamin Peterson90c58022010-03-03 01:55:09 +0000637The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000638
Georg Brandlb8d0e362010-11-26 07:53:50 +0000639
Benjamin Petersona39e9662010-03-02 22:05:59 +0000640name or flags
641^^^^^^^^^^^^^
642
Ezio Melottic69313a2011-04-22 01:29:13 +0300643The :meth:`~ArgumentParser.add_argument` method must know whether an optional
644argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
645filenames, is expected. The first arguments passed to
646:meth:`~ArgumentParser.add_argument` must therefore be either a series of
647flags, or a simple argument name. For example, an optional argument could
648be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000649
650 >>> parser.add_argument('-f', '--foo')
651
652while a positional argument could be created like::
653
654 >>> parser.add_argument('bar')
655
Ezio Melottic69313a2011-04-22 01:29:13 +0300656When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
657identified by the ``-`` prefix, and the remaining arguments will be assumed to
658be positional::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000659
660 >>> parser = argparse.ArgumentParser(prog='PROG')
661 >>> parser.add_argument('-f', '--foo')
662 >>> parser.add_argument('bar')
663 >>> parser.parse_args(['BAR'])
664 Namespace(bar='BAR', foo=None)
665 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
666 Namespace(bar='BAR', foo='FOO')
667 >>> parser.parse_args(['--foo', 'FOO'])
668 usage: PROG [-h] [-f FOO] bar
669 PROG: error: too few arguments
670
Georg Brandlb8d0e362010-11-26 07:53:50 +0000671
Benjamin Petersona39e9662010-03-02 22:05:59 +0000672action
673^^^^^^
674
Éric Araujo67719bd2011-08-19 02:00:07 +0200675:class:`ArgumentParser` objects associate command-line arguments with actions. These
676actions can do just about anything with the command-line arguments associated with
Benjamin Petersona39e9662010-03-02 22:05:59 +0000677them, though most actions simply add an attribute to the object returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300678:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombs2c34fb52011-12-13 23:36:45 -0500679how the command-line arguments should be handled. The supplied actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000680
Georg Brandld2decd92010-03-02 22:17:38 +0000681* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300682 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000683
684 >>> parser = argparse.ArgumentParser()
685 >>> parser.add_argument('--foo')
686 >>> parser.parse_args('--foo 1'.split())
687 Namespace(foo='1')
688
689* ``'store_const'`` - This stores the value specified by the const_ keyword
Martin Panter87d9de62016-04-09 03:49:48 +0000690 argument. The ``'store_const'`` action is most commonly used with
Ezio Melotti310619c2011-04-21 23:06:48 +0300691 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000692
693 >>> parser = argparse.ArgumentParser()
694 >>> parser.add_argument('--foo', action='store_const', const=42)
Martin Panter11cc5132016-04-26 11:33:46 +0000695 >>> parser.parse_args(['--foo'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000696 Namespace(foo=42)
697
Raymond Hettinger421467f2011-11-20 11:05:23 -0800698* ``'store_true'`` and ``'store_false'`` - These are special cases of
699 ``'store_const'`` using for storing the values ``True`` and ``False``
Serhiy Storchakae3d57872016-10-19 16:43:18 +0300700 respectively. In addition, they create default values of ``False`` and ``True``
Raymond Hettinger421467f2011-11-20 11:05:23 -0800701 respectively. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000702
703 >>> parser = argparse.ArgumentParser()
704 >>> parser.add_argument('--foo', action='store_true')
705 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettinger421467f2011-11-20 11:05:23 -0800706 >>> parser.add_argument('--baz', action='store_false')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000707 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettinger421467f2011-11-20 11:05:23 -0800708 Namespace(bar=False, baz=True, foo=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000709
710* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000711 list. This is useful to allow an option to be specified multiple times.
712 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000713
714 >>> parser = argparse.ArgumentParser()
715 >>> parser.add_argument('--foo', action='append')
716 >>> parser.parse_args('--foo 1 --foo 2'.split())
717 Namespace(foo=['1', '2'])
718
719* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000720 the const_ keyword argument to the list. (Note that the const_ keyword
721 argument defaults to ``None``.) The ``'append_const'`` action is typically
722 useful when multiple arguments need to store constants to the same list. For
723 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000724
725 >>> parser = argparse.ArgumentParser()
726 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
727 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
728 >>> parser.parse_args('--str --int'.split())
729 Namespace(types=[<type 'str'>, <type 'int'>])
730
Sandro Tosi8b211fc2012-01-04 23:24:48 +0100731* ``'count'`` - This counts the number of times a keyword argument occurs. For
732 example, this is useful for increasing verbosity levels::
733
734 >>> parser = argparse.ArgumentParser()
735 >>> parser.add_argument('--verbose', '-v', action='count')
Martin Panter11cc5132016-04-26 11:33:46 +0000736 >>> parser.parse_args(['-vvv'])
Sandro Tosi8b211fc2012-01-04 23:24:48 +0100737 Namespace(verbose=3)
738
739* ``'help'`` - This prints a complete help message for all the options in the
740 current parser and then exits. By default a help action is automatically
741 added to the parser. See :class:`ArgumentParser` for details of how the
742 output is created.
743
Benjamin Petersona39e9662010-03-02 22:05:59 +0000744* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melottic69313a2011-04-22 01:29:13 +0300745 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujobb42f5e2012-02-20 02:08:01 +0100746 and exits when invoked::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000747
748 >>> import argparse
749 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000750 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
751 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000752 PROG 2.0
753
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400754You may also specify an arbitrary action by passing an Action subclass or
755other object that implements the same interface. The recommended way to do
Jason R. Coombs2b492032014-08-03 14:54:11 -0400756this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400757and optionally the ``__init__`` method.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000758
Benjamin Peterson90c58022010-03-03 01:55:09 +0000759An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000760
761 >>> class FooAction(argparse.Action):
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400762 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
763 ... if nargs is not None:
764 ... raise ValueError("nargs not allowed")
765 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000766 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000767 ... print '%r %r %r' % (namespace, values, option_string)
768 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000769 ...
770 >>> parser = argparse.ArgumentParser()
771 >>> parser.add_argument('--foo', action=FooAction)
772 >>> parser.add_argument('bar', action=FooAction)
773 >>> args = parser.parse_args('1 --foo 2'.split())
774 Namespace(bar=None, foo=None) '1' None
775 Namespace(bar='1', foo=None) '2' '--foo'
776 >>> args
777 Namespace(bar='1', foo='2')
778
Jason R. Coombs2b492032014-08-03 14:54:11 -0400779For more details, see :class:`Action`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000780
781nargs
782^^^^^
783
784ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000785single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300786different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000787values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000788
Éric Araujobb42f5e2012-02-20 02:08:01 +0100789* ``N`` (an integer). ``N`` arguments from the command line will be gathered
790 together into a list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000791
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000792 >>> parser = argparse.ArgumentParser()
793 >>> parser.add_argument('--foo', nargs=2)
794 >>> parser.add_argument('bar', nargs=1)
795 >>> parser.parse_args('c --foo a b'.split())
796 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000797
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000798 Note that ``nargs=1`` produces a list of one item. This is different from
799 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000800
Éric Araujo67719bd2011-08-19 02:00:07 +0200801* ``'?'``. One argument will be consumed from the command line if possible, and
802 produced as a single item. If no command-line argument is present, the value from
Benjamin Petersona39e9662010-03-02 22:05:59 +0000803 default_ will be produced. Note that for optional arguments, there is an
804 additional case - the option string is present but not followed by a
Éric Araujo67719bd2011-08-19 02:00:07 +0200805 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Petersona39e9662010-03-02 22:05:59 +0000806 examples to illustrate this::
807
Georg Brandld2decd92010-03-02 22:17:38 +0000808 >>> parser = argparse.ArgumentParser()
809 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
810 >>> parser.add_argument('bar', nargs='?', default='d')
Martin Panter11cc5132016-04-26 11:33:46 +0000811 >>> parser.parse_args(['XX', '--foo', 'YY'])
Georg Brandld2decd92010-03-02 22:17:38 +0000812 Namespace(bar='XX', foo='YY')
Martin Panter11cc5132016-04-26 11:33:46 +0000813 >>> parser.parse_args(['XX', '--foo'])
Georg Brandld2decd92010-03-02 22:17:38 +0000814 Namespace(bar='XX', foo='c')
Martin Panter11cc5132016-04-26 11:33:46 +0000815 >>> parser.parse_args([])
Georg Brandld2decd92010-03-02 22:17:38 +0000816 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000817
Georg Brandld2decd92010-03-02 22:17:38 +0000818 One of the more common uses of ``nargs='?'`` is to allow optional input and
819 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000820
Georg Brandld2decd92010-03-02 22:17:38 +0000821 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000822 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
823 ... default=sys.stdin)
824 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
825 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000826 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000827 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
828 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000829 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000830 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
831 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000832
Éric Araujo67719bd2011-08-19 02:00:07 +0200833* ``'*'``. All command-line arguments present are gathered into a list. Note that
Georg Brandld2decd92010-03-02 22:17:38 +0000834 it generally doesn't make much sense to have more than one positional argument
835 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
836 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000837
Georg Brandld2decd92010-03-02 22:17:38 +0000838 >>> parser = argparse.ArgumentParser()
839 >>> parser.add_argument('--foo', nargs='*')
840 >>> parser.add_argument('--bar', nargs='*')
841 >>> parser.add_argument('baz', nargs='*')
842 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
843 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000844
845* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
846 list. Additionally, an error message will be generated if there wasn't at
Éric Araujo67719bd2011-08-19 02:00:07 +0200847 least one command-line argument present. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000848
Georg Brandld2decd92010-03-02 22:17:38 +0000849 >>> parser = argparse.ArgumentParser(prog='PROG')
850 >>> parser.add_argument('foo', nargs='+')
Martin Panter11cc5132016-04-26 11:33:46 +0000851 >>> parser.parse_args(['a', 'b'])
Georg Brandld2decd92010-03-02 22:17:38 +0000852 Namespace(foo=['a', 'b'])
Martin Panter11cc5132016-04-26 11:33:46 +0000853 >>> parser.parse_args([])
Georg Brandld2decd92010-03-02 22:17:38 +0000854 usage: PROG [-h] foo [foo ...]
855 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000856
R. David Murrayae16b992017-09-10 01:55:07 -0400857.. _`argparse.REMAINDER`:
858
Sandro Tosicb212272012-01-19 22:22:35 +0100859* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
860 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujobb42f5e2012-02-20 02:08:01 +0100861 to other command line utilities::
Sandro Tosi10f047d2012-01-19 21:59:34 +0100862
863 >>> parser = argparse.ArgumentParser(prog='PROG')
864 >>> parser.add_argument('--foo')
865 >>> parser.add_argument('command')
866 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosicb212272012-01-19 22:22:35 +0100867 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
868 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi10f047d2012-01-19 21:59:34 +0100869
Éric Araujo67719bd2011-08-19 02:00:07 +0200870If the ``nargs`` keyword argument is not provided, the number of arguments consumed
871is determined by the action_. Generally this means a single command-line argument
Benjamin Petersona39e9662010-03-02 22:05:59 +0000872will be consumed and a single item (not a list) will be produced.
873
874
875const
876^^^^^
877
Ezio Melottic69313a2011-04-22 01:29:13 +0300878The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
879constant values that are not read from the command line but are required for
880the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000881
Ezio Melottic69313a2011-04-22 01:29:13 +0300882* When :meth:`~ArgumentParser.add_argument` is called with
883 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujobb42f5e2012-02-20 02:08:01 +0100884 ``const`` value to one of the attributes of the object returned by
885 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000886
Ezio Melottic69313a2011-04-22 01:29:13 +0300887* When :meth:`~ArgumentParser.add_argument` is called with option strings
888 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujo67719bd2011-08-19 02:00:07 +0200889 argument that can be followed by zero or one command-line arguments.
Ezio Melottic69313a2011-04-22 01:29:13 +0300890 When parsing the command line, if the option string is encountered with no
Éric Araujo67719bd2011-08-19 02:00:07 +0200891 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melottic69313a2011-04-22 01:29:13 +0300892 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000893
Martin Panter87d9de62016-04-09 03:49:48 +0000894With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panterbf02d182016-04-16 09:28:57 +0000895keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000896
897
898default
899^^^^^^^
900
901All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300902command line. The ``default`` keyword argument of
903:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujo67719bd2011-08-19 02:00:07 +0200904specifies what value should be used if the command-line argument is not present.
Ezio Melottic69313a2011-04-22 01:29:13 +0300905For optional arguments, the ``default`` value is used when the option string
906was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000907
908 >>> parser = argparse.ArgumentParser()
909 >>> parser.add_argument('--foo', default=42)
Martin Panter11cc5132016-04-26 11:33:46 +0000910 >>> parser.parse_args(['--foo', '2'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000911 Namespace(foo='2')
Martin Panter11cc5132016-04-26 11:33:46 +0000912 >>> parser.parse_args([])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000913 Namespace(foo=42)
914
Barry Warsaw0dea9362012-09-25 10:32:53 -0400915If the ``default`` value is a string, the parser parses the value as if it
916were a command-line argument. In particular, the parser applies any type_
917conversion argument, if provided, before setting the attribute on the
918:class:`Namespace` return value. Otherwise, the parser uses the value as is::
919
920 >>> parser = argparse.ArgumentParser()
921 >>> parser.add_argument('--length', default='10', type=int)
922 >>> parser.add_argument('--width', default=10.5, type=int)
923 >>> parser.parse_args()
924 Namespace(length=10, width=10.5)
925
Éric Araujo67719bd2011-08-19 02:00:07 +0200926For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
927is used when no command-line argument was present::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000928
929 >>> parser = argparse.ArgumentParser()
930 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panter11cc5132016-04-26 11:33:46 +0000931 >>> parser.parse_args(['a'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000932 Namespace(foo='a')
Martin Panter11cc5132016-04-26 11:33:46 +0000933 >>> parser.parse_args([])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000934 Namespace(foo=42)
935
936
Benjamin Peterson90c58022010-03-03 01:55:09 +0000937Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
938command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000939
940 >>> parser = argparse.ArgumentParser()
941 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
942 >>> parser.parse_args([])
943 Namespace()
944 >>> parser.parse_args(['--foo', '1'])
945 Namespace(foo='1')
946
947
948type
949^^^^
950
Éric Araujo67719bd2011-08-19 02:00:07 +0200951By default, :class:`ArgumentParser` objects read command-line arguments in as simple
952strings. However, quite often the command-line string should instead be
953interpreted as another type, like a :class:`float` or :class:`int`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300954``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujo67719bd2011-08-19 02:00:07 +0200955necessary type-checking and type conversions to be performed. Common built-in
956types and functions can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000957
958 >>> parser = argparse.ArgumentParser()
959 >>> parser.add_argument('foo', type=int)
960 >>> parser.add_argument('bar', type=file)
961 >>> parser.parse_args('2 temp.txt'.split())
962 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
963
Barry Warsaw0dea9362012-09-25 10:32:53 -0400964See the section on the default_ keyword argument for information on when the
965``type`` argument is applied to default arguments.
966
Benjamin Petersona39e9662010-03-02 22:05:59 +0000967To ease the use of various types of files, the argparse module provides the
968factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000969``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000970writable file::
971
972 >>> parser = argparse.ArgumentParser()
973 >>> parser.add_argument('bar', type=argparse.FileType('w'))
974 >>> parser.parse_args(['out.txt'])
975 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
976
Benjamin Peterson90c58022010-03-03 01:55:09 +0000977``type=`` can take any callable that takes a single string argument and returns
Éric Araujo67719bd2011-08-19 02:00:07 +0200978the converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000979
980 >>> def perfect_square(string):
981 ... value = int(string)
982 ... sqrt = math.sqrt(value)
983 ... if sqrt != int(sqrt):
984 ... msg = "%r is not a perfect square" % string
985 ... raise argparse.ArgumentTypeError(msg)
986 ... return value
987 ...
988 >>> parser = argparse.ArgumentParser(prog='PROG')
989 >>> parser.add_argument('foo', type=perfect_square)
Martin Panter11cc5132016-04-26 11:33:46 +0000990 >>> parser.parse_args(['9'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000991 Namespace(foo=9)
Martin Panter11cc5132016-04-26 11:33:46 +0000992 >>> parser.parse_args(['7'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000993 usage: PROG [-h] foo
994 PROG: error: argument foo: '7' is not a perfect square
995
Benjamin Peterson90c58022010-03-03 01:55:09 +0000996The choices_ keyword argument may be more convenient for type checkers that
997simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000998
999 >>> parser = argparse.ArgumentParser(prog='PROG')
1000 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
Martin Panter11cc5132016-04-26 11:33:46 +00001001 >>> parser.parse_args(['7'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001002 Namespace(foo=7)
Martin Panter11cc5132016-04-26 11:33:46 +00001003 >>> parser.parse_args(['11'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001004 usage: PROG [-h] {5,6,7,8,9}
1005 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1006
1007See the choices_ section for more details.
1008
1009
1010choices
1011^^^^^^^
1012
Éric Araujo67719bd2011-08-19 02:00:07 +02001013Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001014These can be handled by passing a container object as the *choices* keyword
Ezio Melottic69313a2011-04-22 01:29:13 +03001015argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001016parsed, argument values will be checked, and an error message will be displayed
1017if the argument was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001018
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001019 >>> parser = argparse.ArgumentParser(prog='game.py')
1020 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1021 >>> parser.parse_args(['rock'])
1022 Namespace(move='rock')
1023 >>> parser.parse_args(['fire'])
1024 usage: game.py [-h] {rock,paper,scissors}
1025 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1026 'paper', 'scissors')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001027
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001028Note that inclusion in the *choices* container is checked after any type_
1029conversions have been performed, so the type of the objects in the *choices*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001030container should match the type_ specified::
1031
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001032 >>> parser = argparse.ArgumentParser(prog='doors.py')
1033 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1034 >>> print(parser.parse_args(['3']))
1035 Namespace(door=3)
1036 >>> parser.parse_args(['4'])
1037 usage: doors.py [-h] {1,2,3}
1038 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001039
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001040Any object that supports the ``in`` operator can be passed as the *choices*
Georg Brandld2decd92010-03-02 22:17:38 +00001041value, so :class:`dict` objects, :class:`set` objects, custom containers,
1042etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001043
1044
1045required
1046^^^^^^^^
1047
Ezio Melotti01b600c2011-04-21 16:12:17 +03001048In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +03001049indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001050To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +03001051keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001052
1053 >>> parser = argparse.ArgumentParser()
1054 >>> parser.add_argument('--foo', required=True)
1055 >>> parser.parse_args(['--foo', 'BAR'])
1056 Namespace(foo='BAR')
1057 >>> parser.parse_args([])
1058 usage: argparse.py [-h] [--foo FOO]
1059 argparse.py: error: option --foo is required
1060
Ezio Melottic69313a2011-04-22 01:29:13 +03001061As the example shows, if an option is marked as ``required``,
1062:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1063present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001064
Benjamin Peterson90c58022010-03-03 01:55:09 +00001065.. note::
1066
1067 Required options are generally considered bad form because users expect
1068 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001069
1070
1071help
1072^^^^
1073
Benjamin Peterson90c58022010-03-03 01:55:09 +00001074The ``help`` value is a string containing a brief description of the argument.
1075When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001076command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001077argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001078
1079 >>> parser = argparse.ArgumentParser(prog='frobble')
1080 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001081 ... help='foo the bars before frobbling')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001082 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001083 ... help='one of the bars to be frobbled')
Martin Panter11cc5132016-04-26 11:33:46 +00001084 >>> parser.parse_args(['-h'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001085 usage: frobble [-h] [--foo] bar [bar ...]
1086
1087 positional arguments:
1088 bar one of the bars to be frobbled
1089
1090 optional arguments:
1091 -h, --help show this help message and exit
1092 --foo foo the bars before frobbling
1093
1094The ``help`` strings can include various format specifiers to avoid repetition
1095of things like the program name or the argument default_. The available
1096specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001097:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001098
1099 >>> parser = argparse.ArgumentParser(prog='frobble')
1100 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001101 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001102 >>> parser.print_help()
1103 usage: frobble [-h] [bar]
1104
1105 positional arguments:
1106 bar the bar to frobble (default: 42)
1107
1108 optional arguments:
1109 -h, --help show this help message and exit
1110
Sandro Tosi711f5472012-01-03 18:31:51 +01001111:mod:`argparse` supports silencing the help entry for certain options, by
1112setting the ``help`` value to ``argparse.SUPPRESS``::
1113
1114 >>> parser = argparse.ArgumentParser(prog='frobble')
1115 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1116 >>> parser.print_help()
1117 usage: frobble [-h]
1118
1119 optional arguments:
1120 -h, --help show this help message and exit
1121
Benjamin Petersona39e9662010-03-02 22:05:59 +00001122
1123metavar
1124^^^^^^^
1125
Sandro Tosi2534f9a2013-01-11 10:48:34 +01001126When :class:`ArgumentParser` generates help messages, it needs some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001127to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001128value as the "name" of each object. By default, for positional argument
1129actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001130the dest_ value is uppercased. So, a single positional argument with
Eli Benderskybba1dd52011-11-11 16:42:11 +02001131``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujo67719bd2011-08-19 02:00:07 +02001132optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson90c58022010-03-03 01:55:09 +00001133will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001134
1135 >>> parser = argparse.ArgumentParser()
1136 >>> parser.add_argument('--foo')
1137 >>> parser.add_argument('bar')
1138 >>> parser.parse_args('X --foo Y'.split())
1139 Namespace(bar='X', foo='Y')
1140 >>> parser.print_help()
1141 usage: [-h] [--foo FOO] bar
1142
1143 positional arguments:
1144 bar
1145
1146 optional arguments:
1147 -h, --help show this help message and exit
1148 --foo FOO
1149
Benjamin Peterson90c58022010-03-03 01:55:09 +00001150An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001151
1152 >>> parser = argparse.ArgumentParser()
1153 >>> parser.add_argument('--foo', metavar='YYY')
1154 >>> parser.add_argument('bar', metavar='XXX')
1155 >>> parser.parse_args('X --foo Y'.split())
1156 Namespace(bar='X', foo='Y')
1157 >>> parser.print_help()
1158 usage: [-h] [--foo YYY] XXX
1159
1160 positional arguments:
1161 XXX
1162
1163 optional arguments:
1164 -h, --help show this help message and exit
1165 --foo YYY
1166
1167Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001168attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1169by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001170
1171Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001172Providing a tuple to ``metavar`` specifies a different display for each of the
1173arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001174
1175 >>> parser = argparse.ArgumentParser(prog='PROG')
1176 >>> parser.add_argument('-x', nargs=2)
1177 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1178 >>> parser.print_help()
1179 usage: PROG [-h] [-x X X] [--foo bar baz]
1180
1181 optional arguments:
1182 -h, --help show this help message and exit
1183 -x X X
1184 --foo bar baz
1185
1186
1187dest
1188^^^^
1189
Benjamin Peterson90c58022010-03-03 01:55:09 +00001190Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001191object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1192attribute is determined by the ``dest`` keyword argument of
1193:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1194``dest`` is normally supplied as the first argument to
1195:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001196
1197 >>> parser = argparse.ArgumentParser()
1198 >>> parser.add_argument('bar')
Martin Panter11cc5132016-04-26 11:33:46 +00001199 >>> parser.parse_args(['XXX'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001200 Namespace(bar='XXX')
1201
1202For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001203the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo67719bd2011-08-19 02:00:07 +02001204taking the first long option string and stripping away the initial ``--``
Benjamin Petersona39e9662010-03-02 22:05:59 +00001205string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo67719bd2011-08-19 02:00:07 +02001206the first short option string by stripping the initial ``-`` character. Any
1207internal ``-`` characters will be converted to ``_`` characters to make sure
Georg Brandld2decd92010-03-02 22:17:38 +00001208the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001209behavior::
1210
1211 >>> parser = argparse.ArgumentParser()
1212 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1213 >>> parser.add_argument('-x', '-y')
1214 >>> parser.parse_args('-f 1 -x 2'.split())
1215 Namespace(foo_bar='1', x='2')
1216 >>> parser.parse_args('--foo 1 -y 2'.split())
1217 Namespace(foo_bar='1', x='2')
1218
Benjamin Peterson90c58022010-03-03 01:55:09 +00001219``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001220
1221 >>> parser = argparse.ArgumentParser()
1222 >>> parser.add_argument('--foo', dest='bar')
1223 >>> parser.parse_args('--foo XXX'.split())
1224 Namespace(bar='XXX')
1225
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001226Action classes
1227^^^^^^^^^^^^^^
1228
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001229Action classes implement the Action API, a callable which returns a callable
Benjamin Petersonceb0e1d2014-09-04 11:50:14 -04001230which processes arguments from the command-line. Any object which follows this
1231API may be passed as the ``action`` parameter to :meth:`add_argument`.
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001232
Berker Peksag80154582015-01-06 18:29:04 +02001233.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1234 type=None, choices=None, required=False, help=None, \
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001235 metavar=None)
1236
Benjamin Petersonceb0e1d2014-09-04 11:50:14 -04001237Action objects are used by an ArgumentParser to represent the information needed
1238to parse a single argument from one or more strings from the command line. The
1239Action class must accept the two positional arguments plus any keyword arguments
1240passed to :meth:`ArgumentParser.add_argument` except for the ``action`` itself.
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001241
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001242Instances of Action (or return value of any callable to the ``action``
1243parameter) should have attributes "dest", "option_strings", "default", "type",
1244"required", "help", etc. defined. The easiest way to ensure these attributes
1245are defined is to call ``Action.__init__``.
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001246
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001247Action instances should be callable, so subclasses must override the
1248``__call__`` method, which should accept four parameters:
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001249
1250* ``parser`` - The ArgumentParser object which contains this action.
1251
1252* ``namespace`` - The :class:`Namespace` object that will be returned by
1253 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1254 object using :func:`setattr`.
1255
1256* ``values`` - The associated command-line arguments, with any type conversions
1257 applied. Type conversions are specified with the type_ keyword argument to
1258 :meth:`~ArgumentParser.add_argument`.
1259
1260* ``option_string`` - The option string that was used to invoke this action.
1261 The ``option_string`` argument is optional, and will be absent if the action
1262 is associated with a positional argument.
1263
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001264The ``__call__`` method may perform arbitrary actions, but will typically set
1265attributes on the ``namespace`` based on ``dest`` and ``values``.
1266
Benjamin Petersona39e9662010-03-02 22:05:59 +00001267
1268The parse_args() method
1269-----------------------
1270
Georg Brandlb8d0e362010-11-26 07:53:50 +00001271.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001272
Benjamin Peterson90c58022010-03-03 01:55:09 +00001273 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001274 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001275
1276 Previous calls to :meth:`add_argument` determine exactly what objects are
1277 created and how they are assigned. See the documentation for
1278 :meth:`add_argument` for details.
1279
R. David Murrayae16b992017-09-10 01:55:07 -04001280 * args_ - List of strings to parse. The default is taken from
1281 :data:`sys.argv`.
1282
1283 * namespace_ - An object to take the attributes. The default is a new empty
1284 :class:`Namespace` object.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001285
Georg Brandlb8d0e362010-11-26 07:53:50 +00001286
Benjamin Petersona39e9662010-03-02 22:05:59 +00001287Option value syntax
1288^^^^^^^^^^^^^^^^^^^
1289
Ezio Melottic69313a2011-04-22 01:29:13 +03001290The :meth:`~ArgumentParser.parse_args` method supports several ways of
1291specifying the value of an option (if it takes one). In the simplest case, the
1292option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001293
1294 >>> parser = argparse.ArgumentParser(prog='PROG')
1295 >>> parser.add_argument('-x')
1296 >>> parser.add_argument('--foo')
Martin Panter11cc5132016-04-26 11:33:46 +00001297 >>> parser.parse_args(['-x', 'X'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001298 Namespace(foo=None, x='X')
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 long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001303and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001304separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001305
Martin Panter11cc5132016-04-26 11:33:46 +00001306 >>> parser.parse_args(['--foo=FOO'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001307 Namespace(foo='FOO', x=None)
1308
Benjamin Peterson90c58022010-03-03 01:55:09 +00001309For short options (options only one character long), the option and its value
1310can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001311
Martin Panter11cc5132016-04-26 11:33:46 +00001312 >>> parser.parse_args(['-xX'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001313 Namespace(foo=None, x='X')
1314
Benjamin Peterson90c58022010-03-03 01:55:09 +00001315Several short options can be joined together, using only a single ``-`` prefix,
1316as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001317
1318 >>> parser = argparse.ArgumentParser(prog='PROG')
1319 >>> parser.add_argument('-x', action='store_true')
1320 >>> parser.add_argument('-y', action='store_true')
1321 >>> parser.add_argument('-z')
Martin Panter11cc5132016-04-26 11:33:46 +00001322 >>> parser.parse_args(['-xyzZ'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001323 Namespace(x=True, y=True, z='Z')
1324
1325
1326Invalid arguments
1327^^^^^^^^^^^^^^^^^
1328
Ezio Melottic69313a2011-04-22 01:29:13 +03001329While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1330variety of errors, including ambiguous options, invalid types, invalid options,
1331wrong number of positional arguments, etc. When it encounters such an error,
1332it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001333
1334 >>> parser = argparse.ArgumentParser(prog='PROG')
1335 >>> parser.add_argument('--foo', type=int)
1336 >>> parser.add_argument('bar', nargs='?')
1337
1338 >>> # invalid type
1339 >>> parser.parse_args(['--foo', 'spam'])
1340 usage: PROG [-h] [--foo FOO] [bar]
1341 PROG: error: argument --foo: invalid int value: 'spam'
1342
1343 >>> # invalid option
1344 >>> parser.parse_args(['--bar'])
1345 usage: PROG [-h] [--foo FOO] [bar]
1346 PROG: error: no such option: --bar
1347
1348 >>> # wrong number of arguments
1349 >>> parser.parse_args(['spam', 'badger'])
1350 usage: PROG [-h] [--foo FOO] [bar]
1351 PROG: error: extra arguments found: badger
1352
1353
Éric Araujo67719bd2011-08-19 02:00:07 +02001354Arguments containing ``-``
1355^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001356
Ezio Melottic69313a2011-04-22 01:29:13 +03001357The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1358the user has clearly made a mistake, but some situations are inherently
Éric Araujo67719bd2011-08-19 02:00:07 +02001359ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melottic69313a2011-04-22 01:29:13 +03001360attempt to specify an option or an attempt to provide a positional argument.
1361The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo67719bd2011-08-19 02:00:07 +02001362arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melottic69313a2011-04-22 01:29:13 +03001363there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001364
1365 >>> parser = argparse.ArgumentParser(prog='PROG')
1366 >>> parser.add_argument('-x')
1367 >>> parser.add_argument('foo', nargs='?')
1368
1369 >>> # no negative number options, so -1 is a positional argument
1370 >>> parser.parse_args(['-x', '-1'])
1371 Namespace(foo=None, x='-1')
1372
1373 >>> # no negative number options, so -1 and -5 are positional arguments
1374 >>> parser.parse_args(['-x', '-1', '-5'])
1375 Namespace(foo='-5', x='-1')
1376
1377 >>> parser = argparse.ArgumentParser(prog='PROG')
1378 >>> parser.add_argument('-1', dest='one')
1379 >>> parser.add_argument('foo', nargs='?')
1380
1381 >>> # negative number options present, so -1 is an option
1382 >>> parser.parse_args(['-1', 'X'])
1383 Namespace(foo=None, one='X')
1384
1385 >>> # negative number options present, so -2 is an option
1386 >>> parser.parse_args(['-2'])
1387 usage: PROG [-h] [-1 ONE] [foo]
1388 PROG: error: no such option: -2
1389
1390 >>> # negative number options present, so both -1s are options
1391 >>> parser.parse_args(['-1', '-1'])
1392 usage: PROG [-h] [-1 ONE] [foo]
1393 PROG: error: argument -1: expected one argument
1394
Éric Araujo67719bd2011-08-19 02:00:07 +02001395If you have positional arguments that must begin with ``-`` and don't look
Benjamin Petersona39e9662010-03-02 22:05:59 +00001396like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001397:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1398argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001399
1400 >>> parser.parse_args(['--', '-f'])
1401 Namespace(foo='-f', one=None)
1402
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001403.. _prefix-matching:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001404
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001405Argument abbreviations (prefix matching)
1406^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001407
Ezio Melottic69313a2011-04-22 01:29:13 +03001408The :meth:`~ArgumentParser.parse_args` method allows long options to be
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001409abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
1410a unique option)::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001411
1412 >>> parser = argparse.ArgumentParser(prog='PROG')
1413 >>> parser.add_argument('-bacon')
1414 >>> parser.add_argument('-badger')
1415 >>> parser.parse_args('-bac MMM'.split())
1416 Namespace(bacon='MMM', badger=None)
1417 >>> parser.parse_args('-bad WOOD'.split())
1418 Namespace(bacon=None, badger='WOOD')
1419 >>> parser.parse_args('-ba BA'.split())
1420 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1421 PROG: error: ambiguous option: -ba could match -badger, -bacon
1422
Benjamin Peterson90c58022010-03-03 01:55:09 +00001423An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001424
R. David Murrayae16b992017-09-10 01:55:07 -04001425.. _args:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001426
1427Beyond ``sys.argv``
1428^^^^^^^^^^^^^^^^^^^
1429
Éric Araujo67719bd2011-08-19 02:00:07 +02001430Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Georg Brandld2decd92010-03-02 22:17:38 +00001431of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001432:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1433interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001434
1435 >>> parser = argparse.ArgumentParser()
1436 >>> parser.add_argument(
1437 ... 'integers', metavar='int', type=int, choices=xrange(10),
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001438 ... nargs='+', help='an integer in the range 0..9')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001439 >>> parser.add_argument(
1440 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001441 ... default=max, help='sum the integers (default: find the max)')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001442 >>> parser.parse_args(['1', '2', '3', '4'])
1443 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panter11cc5132016-04-26 11:33:46 +00001444 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001445 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1446
R. David Murrayae16b992017-09-10 01:55:07 -04001447.. _namespace:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001448
Steven Bethard3f69a052011-03-26 19:59:02 +01001449The Namespace object
1450^^^^^^^^^^^^^^^^^^^^
1451
Éric Araujof0d44bc2011-07-29 17:59:17 +02001452.. class:: Namespace
1453
1454 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1455 an object holding attributes and return it.
1456
1457This class is deliberately simple, just an :class:`object` subclass with a
1458readable string representation. If you prefer to have dict-like view of the
1459attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001460
1461 >>> parser = argparse.ArgumentParser()
1462 >>> parser.add_argument('--foo')
1463 >>> args = parser.parse_args(['--foo', 'BAR'])
1464 >>> vars(args)
1465 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001466
Benjamin Peterson90c58022010-03-03 01:55:09 +00001467It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001468already existing object, rather than a new :class:`Namespace` object. This can
1469be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001470
1471 >>> class C(object):
1472 ... pass
1473 ...
1474 >>> c = C()
1475 >>> parser = argparse.ArgumentParser()
1476 >>> parser.add_argument('--foo')
1477 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1478 >>> c.foo
1479 'BAR'
1480
1481
1482Other utilities
1483---------------
1484
1485Sub-commands
1486^^^^^^^^^^^^
1487
Georg Brandl1f94b262013-10-06 18:51:39 +02001488.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1489 [parser_class], [action], \
1490 [option_string], [dest], [help], \
1491 [metavar])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001492
Benjamin Peterson90c58022010-03-03 01:55:09 +00001493 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001494 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001495 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001496 this way can be a particularly good idea when a program performs several
1497 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001498 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001499 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti82ee3032012-12-28 01:59:24 +02001500 called with no arguments and returns a special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001501 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1502 command name and any :class:`ArgumentParser` constructor arguments, and
1503 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001504
Georg Brandl1f94b262013-10-06 18:51:39 +02001505 Description of parameters:
1506
1507 * title - title for the sub-parser group in help output; by default
1508 "subcommands" if description is provided, otherwise uses title for
1509 positional arguments
1510
1511 * description - description for the sub-parser group in help output, by
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001512 default ``None``
Georg Brandl1f94b262013-10-06 18:51:39 +02001513
1514 * prog - usage information that will be displayed with sub-command help,
1515 by default the name of the program and any positional arguments before the
1516 subparser argument
1517
1518 * parser_class - class which will be used to create sub-parser instances, by
1519 default the class of the current parser (e.g. ArgumentParser)
1520
Berker Peksag1b6e5382015-01-20 06:55:51 +02001521 * action_ - the basic type of action to be taken when this argument is
1522 encountered at the command line
1523
1524 * dest_ - name of the attribute under which sub-command name will be
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001525 stored; by default ``None`` and no value is stored
Georg Brandl1f94b262013-10-06 18:51:39 +02001526
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001527 * help_ - help for sub-parser group in help output, by default ``None``
Georg Brandl1f94b262013-10-06 18:51:39 +02001528
Berker Peksag1b6e5382015-01-20 06:55:51 +02001529 * metavar_ - string presenting available sub-commands in help; by default it
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001530 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
Georg Brandl1f94b262013-10-06 18:51:39 +02001531
Benjamin Petersona39e9662010-03-02 22:05:59 +00001532 Some example usage::
1533
1534 >>> # create the top-level parser
1535 >>> parser = argparse.ArgumentParser(prog='PROG')
1536 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1537 >>> subparsers = parser.add_subparsers(help='sub-command help')
1538 >>>
1539 >>> # create the parser for the "a" command
1540 >>> parser_a = subparsers.add_parser('a', help='a help')
1541 >>> parser_a.add_argument('bar', type=int, help='bar help')
1542 >>>
1543 >>> # create the parser for the "b" command
1544 >>> parser_b = subparsers.add_parser('b', help='b help')
1545 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1546 >>>
Éric Araujo67719bd2011-08-19 02:00:07 +02001547 >>> # parse some argument lists
Benjamin Petersona39e9662010-03-02 22:05:59 +00001548 >>> parser.parse_args(['a', '12'])
1549 Namespace(bar=12, foo=False)
1550 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1551 Namespace(baz='Z', foo=True)
1552
1553 Note that the object returned by :meth:`parse_args` will only contain
1554 attributes for the main parser and the subparser that was selected by the
1555 command line (and not any other subparsers). So in the example above, when
Éric Araujo67719bd2011-08-19 02:00:07 +02001556 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1557 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001558 ``baz`` attributes are present.
1559
1560 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001561 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001562 include parent parser or sibling parser messages. (A help message for each
1563 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001564 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001565
1566 ::
1567
1568 >>> parser.parse_args(['--help'])
1569 usage: PROG [-h] [--foo] {a,b} ...
1570
1571 positional arguments:
1572 {a,b} sub-command help
Ezio Melottidc157fc2013-01-12 10:39:45 +02001573 a a help
1574 b b help
Benjamin Petersona39e9662010-03-02 22:05:59 +00001575
1576 optional arguments:
1577 -h, --help show this help message and exit
1578 --foo foo help
1579
1580 >>> parser.parse_args(['a', '--help'])
1581 usage: PROG a [-h] bar
1582
1583 positional arguments:
1584 bar bar help
1585
1586 optional arguments:
1587 -h, --help show this help message and exit
1588
1589 >>> parser.parse_args(['b', '--help'])
1590 usage: PROG b [-h] [--baz {X,Y,Z}]
1591
1592 optional arguments:
1593 -h, --help show this help message and exit
1594 --baz {X,Y,Z} baz help
1595
Georg Brandld2decd92010-03-02 22:17:38 +00001596 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1597 keyword arguments. When either is present, the subparser's commands will
1598 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001599
1600 >>> parser = argparse.ArgumentParser()
1601 >>> subparsers = parser.add_subparsers(title='subcommands',
1602 ... description='valid subcommands',
1603 ... help='additional help')
1604 >>> subparsers.add_parser('foo')
1605 >>> subparsers.add_parser('bar')
1606 >>> parser.parse_args(['-h'])
1607 usage: [-h] {foo,bar} ...
1608
1609 optional arguments:
1610 -h, --help show this help message and exit
1611
1612 subcommands:
1613 valid subcommands
1614
1615 {foo,bar} additional help
1616
1617
Georg Brandld2decd92010-03-02 22:17:38 +00001618 One particularly effective way of handling sub-commands is to combine the use
1619 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1620 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001621 example::
1622
1623 >>> # sub-command functions
1624 >>> def foo(args):
1625 ... print args.x * args.y
1626 ...
1627 >>> def bar(args):
1628 ... print '((%s))' % args.z
1629 ...
1630 >>> # create the top-level parser
1631 >>> parser = argparse.ArgumentParser()
1632 >>> subparsers = parser.add_subparsers()
1633 >>>
1634 >>> # create the parser for the "foo" command
1635 >>> parser_foo = subparsers.add_parser('foo')
1636 >>> parser_foo.add_argument('-x', type=int, default=1)
1637 >>> parser_foo.add_argument('y', type=float)
1638 >>> parser_foo.set_defaults(func=foo)
1639 >>>
1640 >>> # create the parser for the "bar" command
1641 >>> parser_bar = subparsers.add_parser('bar')
1642 >>> parser_bar.add_argument('z')
1643 >>> parser_bar.set_defaults(func=bar)
1644 >>>
1645 >>> # parse the args and call whatever function was selected
1646 >>> args = parser.parse_args('foo 1 -x 2'.split())
1647 >>> args.func(args)
1648 2.0
1649 >>>
1650 >>> # parse the args and call whatever function was selected
1651 >>> args = parser.parse_args('bar XYZYX'.split())
1652 >>> args.func(args)
1653 ((XYZYX))
1654
Éric Araujobb42f5e2012-02-20 02:08:01 +01001655 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson90c58022010-03-03 01:55:09 +00001656 appropriate function after argument parsing is complete. Associating
1657 functions with actions like this is typically the easiest way to handle the
1658 different actions for each of your subparsers. However, if it is necessary
1659 to check the name of the subparser that was invoked, the ``dest`` keyword
1660 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001661
1662 >>> parser = argparse.ArgumentParser()
1663 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1664 >>> subparser1 = subparsers.add_parser('1')
1665 >>> subparser1.add_argument('-x')
1666 >>> subparser2 = subparsers.add_parser('2')
1667 >>> subparser2.add_argument('y')
1668 >>> parser.parse_args(['2', 'frobble'])
1669 Namespace(subparser_name='2', y='frobble')
1670
1671
1672FileType objects
1673^^^^^^^^^^^^^^^^
1674
1675.. class:: FileType(mode='r', bufsize=None)
1676
1677 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001678 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujo67719bd2011-08-19 02:00:07 +02001679 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujobb42f5e2012-02-20 02:08:01 +01001680 with the requested modes and buffer sizes::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001681
Éric Araujobb42f5e2012-02-20 02:08:01 +01001682 >>> parser = argparse.ArgumentParser()
1683 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1684 >>> parser.parse_args(['--output', 'out'])
1685 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001686
1687 FileType objects understand the pseudo-argument ``'-'`` and automatically
1688 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujobb42f5e2012-02-20 02:08:01 +01001689 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001690
Éric Araujobb42f5e2012-02-20 02:08:01 +01001691 >>> parser = argparse.ArgumentParser()
1692 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1693 >>> parser.parse_args(['-'])
1694 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001695
1696
1697Argument groups
1698^^^^^^^^^^^^^^^
1699
Georg Brandlb8d0e362010-11-26 07:53:50 +00001700.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001701
Benjamin Peterson90c58022010-03-03 01:55:09 +00001702 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001703 "positional arguments" and "optional arguments" when displaying help
1704 messages. When there is a better conceptual grouping of arguments than this
1705 default one, appropriate groups can be created using the
1706 :meth:`add_argument_group` method::
1707
1708 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1709 >>> group = parser.add_argument_group('group')
1710 >>> group.add_argument('--foo', help='foo help')
1711 >>> group.add_argument('bar', help='bar help')
1712 >>> parser.print_help()
1713 usage: PROG [--foo FOO] bar
1714
1715 group:
1716 bar bar help
1717 --foo FOO foo help
1718
1719 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001720 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1721 :class:`ArgumentParser`. When an argument is added to the group, the parser
1722 treats it just like a normal argument, but displays the argument in a
1723 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001724 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001725 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001726
1727 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1728 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1729 >>> group1.add_argument('foo', help='foo help')
1730 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1731 >>> group2.add_argument('--bar', help='bar help')
1732 >>> parser.print_help()
1733 usage: PROG [--bar BAR] foo
1734
1735 group1:
1736 group1 description
1737
1738 foo foo help
1739
1740 group2:
1741 group2 description
1742
1743 --bar BAR bar help
1744
Sandro Tosi48a88952012-03-26 19:35:52 +02001745 Note that any arguments not in your user-defined groups will end up back
1746 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001747
1748
1749Mutual exclusion
1750^^^^^^^^^^^^^^^^
1751
Georg Brandle3005462013-10-06 13:09:59 +02001752.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001753
Ezio Melotti01b600c2011-04-21 16:12:17 +03001754 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1755 one of the arguments in the mutually exclusive group was present on the
1756 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001757
1758 >>> parser = argparse.ArgumentParser(prog='PROG')
1759 >>> group = parser.add_mutually_exclusive_group()
1760 >>> group.add_argument('--foo', action='store_true')
1761 >>> group.add_argument('--bar', action='store_false')
1762 >>> parser.parse_args(['--foo'])
1763 Namespace(bar=True, foo=True)
1764 >>> parser.parse_args(['--bar'])
1765 Namespace(bar=False, foo=False)
1766 >>> parser.parse_args(['--foo', '--bar'])
1767 usage: PROG [-h] [--foo | --bar]
1768 PROG: error: argument --bar: not allowed with argument --foo
1769
Georg Brandlb8d0e362010-11-26 07:53:50 +00001770 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001771 argument, to indicate that at least one of the mutually exclusive arguments
1772 is required::
1773
1774 >>> parser = argparse.ArgumentParser(prog='PROG')
1775 >>> group = parser.add_mutually_exclusive_group(required=True)
1776 >>> group.add_argument('--foo', action='store_true')
1777 >>> group.add_argument('--bar', action='store_false')
1778 >>> parser.parse_args([])
1779 usage: PROG [-h] (--foo | --bar)
1780 PROG: error: one of the arguments --foo --bar is required
1781
1782 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001783 *title* and *description* arguments of
1784 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001785
1786
1787Parser defaults
1788^^^^^^^^^^^^^^^
1789
Benjamin Peterson90c58022010-03-03 01:55:09 +00001790.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001791
Georg Brandld2decd92010-03-02 22:17:38 +00001792 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujo67719bd2011-08-19 02:00:07 +02001793 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001794 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001795 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001796 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001797
1798 >>> parser = argparse.ArgumentParser()
1799 >>> parser.add_argument('foo', type=int)
1800 >>> parser.set_defaults(bar=42, baz='badger')
1801 >>> parser.parse_args(['736'])
1802 Namespace(bar=42, baz='badger', foo=736)
1803
Benjamin Peterson90c58022010-03-03 01:55:09 +00001804 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001805
1806 >>> parser = argparse.ArgumentParser()
1807 >>> parser.add_argument('--foo', default='bar')
1808 >>> parser.set_defaults(foo='spam')
1809 >>> parser.parse_args([])
1810 Namespace(foo='spam')
1811
Benjamin Peterson90c58022010-03-03 01:55:09 +00001812 Parser-level defaults can be particularly useful when working with multiple
1813 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1814 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001815
Benjamin Peterson90c58022010-03-03 01:55:09 +00001816.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001817
1818 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001819 :meth:`~ArgumentParser.add_argument` or by
1820 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001821
1822 >>> parser = argparse.ArgumentParser()
1823 >>> parser.add_argument('--foo', default='badger')
1824 >>> parser.get_default('foo')
1825 'badger'
1826
1827
1828Printing help
1829^^^^^^^^^^^^^
1830
Ezio Melottic69313a2011-04-22 01:29:13 +03001831In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1832care of formatting and printing any usage or error messages. However, several
1833formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001834
Georg Brandlb8d0e362010-11-26 07:53:50 +00001835.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001836
1837 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001838 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001839 assumed.
1840
Georg Brandlb8d0e362010-11-26 07:53:50 +00001841.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001842
1843 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001844 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001845 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001846
1847There are also variants of these methods that simply return a string instead of
1848printing it:
1849
Georg Brandlb8d0e362010-11-26 07:53:50 +00001850.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001851
1852 Return a string containing a brief description of how the
1853 :class:`ArgumentParser` should be invoked on the command line.
1854
Georg Brandlb8d0e362010-11-26 07:53:50 +00001855.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001856
1857 Return a string containing a help message, including the program usage and
1858 information about the arguments registered with the :class:`ArgumentParser`.
1859
1860
Benjamin Petersona39e9662010-03-02 22:05:59 +00001861Partial parsing
1862^^^^^^^^^^^^^^^
1863
Georg Brandlb8d0e362010-11-26 07:53:50 +00001864.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001865
Ezio Melotti12125822011-04-16 23:04:51 +03001866Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001867the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001868:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001869:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1870extra arguments are present. Instead, it returns a two item tuple containing
1871the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001872
1873::
1874
1875 >>> parser = argparse.ArgumentParser()
1876 >>> parser.add_argument('--foo', action='store_true')
1877 >>> parser.add_argument('bar')
1878 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1879 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1880
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001881.. warning::
1882 :ref:`Prefix matching <prefix-matching>` rules apply to
1883 :meth:`parse_known_args`. The parser may consume an option even if it's just
1884 a prefix of one of its known options, instead of leaving it in the remaining
1885 arguments list.
1886
Benjamin Petersona39e9662010-03-02 22:05:59 +00001887
1888Customizing file parsing
1889^^^^^^^^^^^^^^^^^^^^^^^^
1890
Benjamin Peterson90c58022010-03-03 01:55:09 +00001891.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001892
Georg Brandlb8d0e362010-11-26 07:53:50 +00001893 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001894 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft5db0b332014-05-20 12:58:38 -04001895 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson90c58022010-03-03 01:55:09 +00001896 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001897
Georg Brandlb8d0e362010-11-26 07:53:50 +00001898 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001899 the argument file. It returns a list of arguments parsed from this string.
1900 The method is called once per line read from the argument file, in order.
1901
Georg Brandld2decd92010-03-02 22:17:38 +00001902 A useful override of this method is one that treats each space-separated word
1903 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001904
1905 def convert_arg_line_to_args(self, arg_line):
Berker Peksag31200ff2015-04-26 12:12:45 +03001906 return arg_line.split()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001907
1908
Georg Brandlb8d0e362010-11-26 07:53:50 +00001909Exiting methods
1910^^^^^^^^^^^^^^^
1911
1912.. method:: ArgumentParser.exit(status=0, message=None)
1913
1914 This method terminates the program, exiting with the specified *status*
1915 and, if given, it prints a *message* before that.
1916
1917.. method:: ArgumentParser.error(message)
1918
1919 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001920 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001921
1922
Georg Brandl58df6792010-07-03 10:25:47 +00001923.. _argparse-from-optparse:
1924
Benjamin Petersona39e9662010-03-02 22:05:59 +00001925Upgrading optparse code
1926-----------------------
1927
Ezio Melottic69313a2011-04-22 01:29:13 +03001928Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001929with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1930transparently, particularly with the changes required to support the new
1931``nargs=`` specifiers and better usage messages. When most everything in
1932:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1933longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001934
Berker Peksag12f05322014-09-26 15:39:05 +03001935The :mod:`argparse` module improves on the standard library :mod:`optparse`
1936module in a number of ways including:
1937
1938* Handling positional arguments.
1939* Supporting sub-commands.
1940* Allowing alternative option prefixes like ``+`` and ``/``.
1941* Handling zero-or-more and one-or-more style arguments.
1942* Producing more informative usage messages.
1943* Providing a much simpler interface for custom ``type`` and ``action``.
1944
Ezio Melotti01b600c2011-04-21 16:12:17 +03001945A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001946
Ezio Melottic69313a2011-04-22 01:29:13 +03001947* Replace all :meth:`optparse.OptionParser.add_option` calls with
1948 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001949
R David Murray5080cad2012-03-30 18:09:07 -04001950* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001951 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5080cad2012-03-30 18:09:07 -04001952 calls for the positional arguments. Keep in mind that what was previously
R. David Murrayae16b992017-09-10 01:55:07 -04001953 called ``options``, now in the :mod:`argparse` context is called ``args``.
1954
1955* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
1956 by setting ``nargs`` of a positional argument to `argparse.REMAINDER`_, or
1957 use :meth:`~ArgumentParser.parse_known_args` to collect unparsed argument
1958 strings in a separate list.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001959
1960* Replace callback actions and the ``callback_*`` keyword arguments with
1961 ``type`` or ``action`` arguments.
1962
1963* Replace string names for ``type`` keyword arguments with the corresponding
1964 type objects (e.g. int, float, complex, etc).
1965
Benjamin Peterson90c58022010-03-03 01:55:09 +00001966* Replace :class:`optparse.Values` with :class:`Namespace` and
1967 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1968 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001969
Georg Brandld2decd92010-03-02 22:17:38 +00001970* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001971 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001972 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001973
1974* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panter4ed35fc2015-10-10 10:52:35 +00001975 ``parser.add_argument('--version', action='version', version='<the version>')``.