blob: c8a5941df722e6fd7aab7db61eb6f9842c915e6c [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
Sandro Tosicb212272012-01-19 22:22:35 +0100857* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
858 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujobb42f5e2012-02-20 02:08:01 +0100859 to other command line utilities::
Sandro Tosi10f047d2012-01-19 21:59:34 +0100860
861 >>> parser = argparse.ArgumentParser(prog='PROG')
862 >>> parser.add_argument('--foo')
863 >>> parser.add_argument('command')
864 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosicb212272012-01-19 22:22:35 +0100865 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
866 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi10f047d2012-01-19 21:59:34 +0100867
Éric Araujo67719bd2011-08-19 02:00:07 +0200868If the ``nargs`` keyword argument is not provided, the number of arguments consumed
869is determined by the action_. Generally this means a single command-line argument
Benjamin Petersona39e9662010-03-02 22:05:59 +0000870will be consumed and a single item (not a list) will be produced.
871
872
873const
874^^^^^
875
Ezio Melottic69313a2011-04-22 01:29:13 +0300876The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
877constant values that are not read from the command line but are required for
878the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000879
Ezio Melottic69313a2011-04-22 01:29:13 +0300880* When :meth:`~ArgumentParser.add_argument` is called with
881 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujobb42f5e2012-02-20 02:08:01 +0100882 ``const`` value to one of the attributes of the object returned by
883 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000884
Ezio Melottic69313a2011-04-22 01:29:13 +0300885* When :meth:`~ArgumentParser.add_argument` is called with option strings
886 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujo67719bd2011-08-19 02:00:07 +0200887 argument that can be followed by zero or one command-line arguments.
Ezio Melottic69313a2011-04-22 01:29:13 +0300888 When parsing the command line, if the option string is encountered with no
Éric Araujo67719bd2011-08-19 02:00:07 +0200889 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melottic69313a2011-04-22 01:29:13 +0300890 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000891
Martin Panter87d9de62016-04-09 03:49:48 +0000892With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
Martin Panterbf02d182016-04-16 09:28:57 +0000893keyword argument must be given. For other actions, it defaults to ``None``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000894
895
896default
897^^^^^^^
898
899All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300900command line. The ``default`` keyword argument of
901:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujo67719bd2011-08-19 02:00:07 +0200902specifies what value should be used if the command-line argument is not present.
Ezio Melottic69313a2011-04-22 01:29:13 +0300903For optional arguments, the ``default`` value is used when the option string
904was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000905
906 >>> parser = argparse.ArgumentParser()
907 >>> parser.add_argument('--foo', default=42)
Martin Panter11cc5132016-04-26 11:33:46 +0000908 >>> parser.parse_args(['--foo', '2'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000909 Namespace(foo='2')
Martin Panter11cc5132016-04-26 11:33:46 +0000910 >>> parser.parse_args([])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000911 Namespace(foo=42)
912
Barry Warsaw0dea9362012-09-25 10:32:53 -0400913If the ``default`` value is a string, the parser parses the value as if it
914were a command-line argument. In particular, the parser applies any type_
915conversion argument, if provided, before setting the attribute on the
916:class:`Namespace` return value. Otherwise, the parser uses the value as is::
917
918 >>> parser = argparse.ArgumentParser()
919 >>> parser.add_argument('--length', default='10', type=int)
920 >>> parser.add_argument('--width', default=10.5, type=int)
921 >>> parser.parse_args()
922 Namespace(length=10, width=10.5)
923
Éric Araujo67719bd2011-08-19 02:00:07 +0200924For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
925is used when no command-line argument was present::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000926
927 >>> parser = argparse.ArgumentParser()
928 >>> parser.add_argument('foo', nargs='?', default=42)
Martin Panter11cc5132016-04-26 11:33:46 +0000929 >>> parser.parse_args(['a'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000930 Namespace(foo='a')
Martin Panter11cc5132016-04-26 11:33:46 +0000931 >>> parser.parse_args([])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000932 Namespace(foo=42)
933
934
Benjamin Peterson90c58022010-03-03 01:55:09 +0000935Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
936command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000937
938 >>> parser = argparse.ArgumentParser()
939 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
940 >>> parser.parse_args([])
941 Namespace()
942 >>> parser.parse_args(['--foo', '1'])
943 Namespace(foo='1')
944
945
946type
947^^^^
948
Éric Araujo67719bd2011-08-19 02:00:07 +0200949By default, :class:`ArgumentParser` objects read command-line arguments in as simple
950strings. However, quite often the command-line string should instead be
951interpreted as another type, like a :class:`float` or :class:`int`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300952``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujo67719bd2011-08-19 02:00:07 +0200953necessary type-checking and type conversions to be performed. Common built-in
954types and functions can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000955
956 >>> parser = argparse.ArgumentParser()
957 >>> parser.add_argument('foo', type=int)
958 >>> parser.add_argument('bar', type=file)
959 >>> parser.parse_args('2 temp.txt'.split())
960 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
961
Barry Warsaw0dea9362012-09-25 10:32:53 -0400962See the section on the default_ keyword argument for information on when the
963``type`` argument is applied to default arguments.
964
Benjamin Petersona39e9662010-03-02 22:05:59 +0000965To ease the use of various types of files, the argparse module provides the
966factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000967``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000968writable file::
969
970 >>> parser = argparse.ArgumentParser()
971 >>> parser.add_argument('bar', type=argparse.FileType('w'))
972 >>> parser.parse_args(['out.txt'])
973 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
974
Benjamin Peterson90c58022010-03-03 01:55:09 +0000975``type=`` can take any callable that takes a single string argument and returns
Éric Araujo67719bd2011-08-19 02:00:07 +0200976the converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000977
978 >>> def perfect_square(string):
979 ... value = int(string)
980 ... sqrt = math.sqrt(value)
981 ... if sqrt != int(sqrt):
982 ... msg = "%r is not a perfect square" % string
983 ... raise argparse.ArgumentTypeError(msg)
984 ... return value
985 ...
986 >>> parser = argparse.ArgumentParser(prog='PROG')
987 >>> parser.add_argument('foo', type=perfect_square)
Martin Panter11cc5132016-04-26 11:33:46 +0000988 >>> parser.parse_args(['9'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000989 Namespace(foo=9)
Martin Panter11cc5132016-04-26 11:33:46 +0000990 >>> parser.parse_args(['7'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000991 usage: PROG [-h] foo
992 PROG: error: argument foo: '7' is not a perfect square
993
Benjamin Peterson90c58022010-03-03 01:55:09 +0000994The choices_ keyword argument may be more convenient for type checkers that
995simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000996
997 >>> parser = argparse.ArgumentParser(prog='PROG')
998 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
Martin Panter11cc5132016-04-26 11:33:46 +0000999 >>> parser.parse_args(['7'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001000 Namespace(foo=7)
Martin Panter11cc5132016-04-26 11:33:46 +00001001 >>> parser.parse_args(['11'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001002 usage: PROG [-h] {5,6,7,8,9}
1003 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
1004
1005See the choices_ section for more details.
1006
1007
1008choices
1009^^^^^^^
1010
Éric Araujo67719bd2011-08-19 02:00:07 +02001011Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001012These can be handled by passing a container object as the *choices* keyword
Ezio Melottic69313a2011-04-22 01:29:13 +03001013argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001014parsed, argument values will be checked, and an error message will be displayed
1015if the argument was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001016
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001017 >>> parser = argparse.ArgumentParser(prog='game.py')
1018 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1019 >>> parser.parse_args(['rock'])
1020 Namespace(move='rock')
1021 >>> parser.parse_args(['fire'])
1022 usage: game.py [-h] {rock,paper,scissors}
1023 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1024 'paper', 'scissors')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001025
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001026Note that inclusion in the *choices* container is checked after any type_
1027conversions have been performed, so the type of the objects in the *choices*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001028container should match the type_ specified::
1029
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001030 >>> parser = argparse.ArgumentParser(prog='doors.py')
1031 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1032 >>> print(parser.parse_args(['3']))
1033 Namespace(door=3)
1034 >>> parser.parse_args(['4'])
1035 usage: doors.py [-h] {1,2,3}
1036 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001037
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001038Any object that supports the ``in`` operator can be passed as the *choices*
Georg Brandld2decd92010-03-02 22:17:38 +00001039value, so :class:`dict` objects, :class:`set` objects, custom containers,
1040etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001041
1042
1043required
1044^^^^^^^^
1045
Ezio Melotti01b600c2011-04-21 16:12:17 +03001046In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +03001047indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001048To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +03001049keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001050
1051 >>> parser = argparse.ArgumentParser()
1052 >>> parser.add_argument('--foo', required=True)
1053 >>> parser.parse_args(['--foo', 'BAR'])
1054 Namespace(foo='BAR')
1055 >>> parser.parse_args([])
1056 usage: argparse.py [-h] [--foo FOO]
1057 argparse.py: error: option --foo is required
1058
Ezio Melottic69313a2011-04-22 01:29:13 +03001059As the example shows, if an option is marked as ``required``,
1060:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1061present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001062
Benjamin Peterson90c58022010-03-03 01:55:09 +00001063.. note::
1064
1065 Required options are generally considered bad form because users expect
1066 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001067
1068
1069help
1070^^^^
1071
Benjamin Peterson90c58022010-03-03 01:55:09 +00001072The ``help`` value is a string containing a brief description of the argument.
1073When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001074command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001075argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001076
1077 >>> parser = argparse.ArgumentParser(prog='frobble')
1078 >>> parser.add_argument('--foo', action='store_true',
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001079 ... help='foo the bars before frobbling')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001080 >>> parser.add_argument('bar', nargs='+',
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001081 ... help='one of the bars to be frobbled')
Martin Panter11cc5132016-04-26 11:33:46 +00001082 >>> parser.parse_args(['-h'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001083 usage: frobble [-h] [--foo] bar [bar ...]
1084
1085 positional arguments:
1086 bar one of the bars to be frobbled
1087
1088 optional arguments:
1089 -h, --help show this help message and exit
1090 --foo foo the bars before frobbling
1091
1092The ``help`` strings can include various format specifiers to avoid repetition
1093of things like the program name or the argument default_. The available
1094specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001095:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001096
1097 >>> parser = argparse.ArgumentParser(prog='frobble')
1098 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001099 ... help='the bar to %(prog)s (default: %(default)s)')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001100 >>> parser.print_help()
1101 usage: frobble [-h] [bar]
1102
1103 positional arguments:
1104 bar the bar to frobble (default: 42)
1105
1106 optional arguments:
1107 -h, --help show this help message and exit
1108
Sandro Tosi711f5472012-01-03 18:31:51 +01001109:mod:`argparse` supports silencing the help entry for certain options, by
1110setting the ``help`` value to ``argparse.SUPPRESS``::
1111
1112 >>> parser = argparse.ArgumentParser(prog='frobble')
1113 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1114 >>> parser.print_help()
1115 usage: frobble [-h]
1116
1117 optional arguments:
1118 -h, --help show this help message and exit
1119
Benjamin Petersona39e9662010-03-02 22:05:59 +00001120
1121metavar
1122^^^^^^^
1123
Sandro Tosi2534f9a2013-01-11 10:48:34 +01001124When :class:`ArgumentParser` generates help messages, it needs some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001125to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001126value as the "name" of each object. By default, for positional argument
1127actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001128the dest_ value is uppercased. So, a single positional argument with
Eli Benderskybba1dd52011-11-11 16:42:11 +02001129``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujo67719bd2011-08-19 02:00:07 +02001130optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson90c58022010-03-03 01:55:09 +00001131will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001132
1133 >>> parser = argparse.ArgumentParser()
1134 >>> parser.add_argument('--foo')
1135 >>> parser.add_argument('bar')
1136 >>> parser.parse_args('X --foo Y'.split())
1137 Namespace(bar='X', foo='Y')
1138 >>> parser.print_help()
1139 usage: [-h] [--foo FOO] bar
1140
1141 positional arguments:
1142 bar
1143
1144 optional arguments:
1145 -h, --help show this help message and exit
1146 --foo FOO
1147
Benjamin Peterson90c58022010-03-03 01:55:09 +00001148An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001149
1150 >>> parser = argparse.ArgumentParser()
1151 >>> parser.add_argument('--foo', metavar='YYY')
1152 >>> parser.add_argument('bar', metavar='XXX')
1153 >>> parser.parse_args('X --foo Y'.split())
1154 Namespace(bar='X', foo='Y')
1155 >>> parser.print_help()
1156 usage: [-h] [--foo YYY] XXX
1157
1158 positional arguments:
1159 XXX
1160
1161 optional arguments:
1162 -h, --help show this help message and exit
1163 --foo YYY
1164
1165Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001166attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1167by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001168
1169Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001170Providing a tuple to ``metavar`` specifies a different display for each of the
1171arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001172
1173 >>> parser = argparse.ArgumentParser(prog='PROG')
1174 >>> parser.add_argument('-x', nargs=2)
1175 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1176 >>> parser.print_help()
1177 usage: PROG [-h] [-x X X] [--foo bar baz]
1178
1179 optional arguments:
1180 -h, --help show this help message and exit
1181 -x X X
1182 --foo bar baz
1183
1184
1185dest
1186^^^^
1187
Benjamin Peterson90c58022010-03-03 01:55:09 +00001188Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001189object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1190attribute is determined by the ``dest`` keyword argument of
1191:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1192``dest`` is normally supplied as the first argument to
1193:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001194
1195 >>> parser = argparse.ArgumentParser()
1196 >>> parser.add_argument('bar')
Martin Panter11cc5132016-04-26 11:33:46 +00001197 >>> parser.parse_args(['XXX'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001198 Namespace(bar='XXX')
1199
1200For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001201the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo67719bd2011-08-19 02:00:07 +02001202taking the first long option string and stripping away the initial ``--``
Benjamin Petersona39e9662010-03-02 22:05:59 +00001203string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo67719bd2011-08-19 02:00:07 +02001204the first short option string by stripping the initial ``-`` character. Any
1205internal ``-`` characters will be converted to ``_`` characters to make sure
Georg Brandld2decd92010-03-02 22:17:38 +00001206the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001207behavior::
1208
1209 >>> parser = argparse.ArgumentParser()
1210 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1211 >>> parser.add_argument('-x', '-y')
1212 >>> parser.parse_args('-f 1 -x 2'.split())
1213 Namespace(foo_bar='1', x='2')
1214 >>> parser.parse_args('--foo 1 -y 2'.split())
1215 Namespace(foo_bar='1', x='2')
1216
Benjamin Peterson90c58022010-03-03 01:55:09 +00001217``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001218
1219 >>> parser = argparse.ArgumentParser()
1220 >>> parser.add_argument('--foo', dest='bar')
1221 >>> parser.parse_args('--foo XXX'.split())
1222 Namespace(bar='XXX')
1223
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001224Action classes
1225^^^^^^^^^^^^^^
1226
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001227Action classes implement the Action API, a callable which returns a callable
Benjamin Petersonceb0e1d2014-09-04 11:50:14 -04001228which processes arguments from the command-line. Any object which follows this
1229API may be passed as the ``action`` parameter to :meth:`add_argument`.
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001230
Berker Peksag80154582015-01-06 18:29:04 +02001231.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1232 type=None, choices=None, required=False, help=None, \
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001233 metavar=None)
1234
Benjamin Petersonceb0e1d2014-09-04 11:50:14 -04001235Action objects are used by an ArgumentParser to represent the information needed
1236to parse a single argument from one or more strings from the command line. The
1237Action class must accept the two positional arguments plus any keyword arguments
1238passed to :meth:`ArgumentParser.add_argument` except for the ``action`` itself.
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001239
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001240Instances of Action (or return value of any callable to the ``action``
1241parameter) should have attributes "dest", "option_strings", "default", "type",
1242"required", "help", etc. defined. The easiest way to ensure these attributes
1243are defined is to call ``Action.__init__``.
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001244
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001245Action instances should be callable, so subclasses must override the
1246``__call__`` method, which should accept four parameters:
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001247
1248* ``parser`` - The ArgumentParser object which contains this action.
1249
1250* ``namespace`` - The :class:`Namespace` object that will be returned by
1251 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1252 object using :func:`setattr`.
1253
1254* ``values`` - The associated command-line arguments, with any type conversions
1255 applied. Type conversions are specified with the type_ keyword argument to
1256 :meth:`~ArgumentParser.add_argument`.
1257
1258* ``option_string`` - The option string that was used to invoke this action.
1259 The ``option_string`` argument is optional, and will be absent if the action
1260 is associated with a positional argument.
1261
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001262The ``__call__`` method may perform arbitrary actions, but will typically set
1263attributes on the ``namespace`` based on ``dest`` and ``values``.
1264
Benjamin Petersona39e9662010-03-02 22:05:59 +00001265
1266The parse_args() method
1267-----------------------
1268
Georg Brandlb8d0e362010-11-26 07:53:50 +00001269.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001270
Benjamin Peterson90c58022010-03-03 01:55:09 +00001271 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001272 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001273
1274 Previous calls to :meth:`add_argument` determine exactly what objects are
1275 created and how they are assigned. See the documentation for
1276 :meth:`add_argument` for details.
1277
Éric Araujo67719bd2011-08-19 02:00:07 +02001278 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001279 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001280
Georg Brandlb8d0e362010-11-26 07:53:50 +00001281
Benjamin Petersona39e9662010-03-02 22:05:59 +00001282Option value syntax
1283^^^^^^^^^^^^^^^^^^^
1284
Ezio Melottic69313a2011-04-22 01:29:13 +03001285The :meth:`~ArgumentParser.parse_args` method supports several ways of
1286specifying the value of an option (if it takes one). In the simplest case, the
1287option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001288
1289 >>> parser = argparse.ArgumentParser(prog='PROG')
1290 >>> parser.add_argument('-x')
1291 >>> parser.add_argument('--foo')
Martin Panter11cc5132016-04-26 11:33:46 +00001292 >>> parser.parse_args(['-x', 'X'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001293 Namespace(foo=None, x='X')
Martin Panter11cc5132016-04-26 11:33:46 +00001294 >>> parser.parse_args(['--foo', 'FOO'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001295 Namespace(foo='FOO', x=None)
1296
Benjamin Peterson90c58022010-03-03 01:55:09 +00001297For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001298and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001299separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001300
Martin Panter11cc5132016-04-26 11:33:46 +00001301 >>> parser.parse_args(['--foo=FOO'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001302 Namespace(foo='FOO', x=None)
1303
Benjamin Peterson90c58022010-03-03 01:55:09 +00001304For short options (options only one character long), the option and its value
1305can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001306
Martin Panter11cc5132016-04-26 11:33:46 +00001307 >>> parser.parse_args(['-xX'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001308 Namespace(foo=None, x='X')
1309
Benjamin Peterson90c58022010-03-03 01:55:09 +00001310Several short options can be joined together, using only a single ``-`` prefix,
1311as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001312
1313 >>> parser = argparse.ArgumentParser(prog='PROG')
1314 >>> parser.add_argument('-x', action='store_true')
1315 >>> parser.add_argument('-y', action='store_true')
1316 >>> parser.add_argument('-z')
Martin Panter11cc5132016-04-26 11:33:46 +00001317 >>> parser.parse_args(['-xyzZ'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001318 Namespace(x=True, y=True, z='Z')
1319
1320
1321Invalid arguments
1322^^^^^^^^^^^^^^^^^
1323
Ezio Melottic69313a2011-04-22 01:29:13 +03001324While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1325variety of errors, including ambiguous options, invalid types, invalid options,
1326wrong number of positional arguments, etc. When it encounters such an error,
1327it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001328
1329 >>> parser = argparse.ArgumentParser(prog='PROG')
1330 >>> parser.add_argument('--foo', type=int)
1331 >>> parser.add_argument('bar', nargs='?')
1332
1333 >>> # invalid type
1334 >>> parser.parse_args(['--foo', 'spam'])
1335 usage: PROG [-h] [--foo FOO] [bar]
1336 PROG: error: argument --foo: invalid int value: 'spam'
1337
1338 >>> # invalid option
1339 >>> parser.parse_args(['--bar'])
1340 usage: PROG [-h] [--foo FOO] [bar]
1341 PROG: error: no such option: --bar
1342
1343 >>> # wrong number of arguments
1344 >>> parser.parse_args(['spam', 'badger'])
1345 usage: PROG [-h] [--foo FOO] [bar]
1346 PROG: error: extra arguments found: badger
1347
1348
Éric Araujo67719bd2011-08-19 02:00:07 +02001349Arguments containing ``-``
1350^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001351
Ezio Melottic69313a2011-04-22 01:29:13 +03001352The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1353the user has clearly made a mistake, but some situations are inherently
Éric Araujo67719bd2011-08-19 02:00:07 +02001354ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melottic69313a2011-04-22 01:29:13 +03001355attempt to specify an option or an attempt to provide a positional argument.
1356The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo67719bd2011-08-19 02:00:07 +02001357arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melottic69313a2011-04-22 01:29:13 +03001358there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001359
1360 >>> parser = argparse.ArgumentParser(prog='PROG')
1361 >>> parser.add_argument('-x')
1362 >>> parser.add_argument('foo', nargs='?')
1363
1364 >>> # no negative number options, so -1 is a positional argument
1365 >>> parser.parse_args(['-x', '-1'])
1366 Namespace(foo=None, x='-1')
1367
1368 >>> # no negative number options, so -1 and -5 are positional arguments
1369 >>> parser.parse_args(['-x', '-1', '-5'])
1370 Namespace(foo='-5', x='-1')
1371
1372 >>> parser = argparse.ArgumentParser(prog='PROG')
1373 >>> parser.add_argument('-1', dest='one')
1374 >>> parser.add_argument('foo', nargs='?')
1375
1376 >>> # negative number options present, so -1 is an option
1377 >>> parser.parse_args(['-1', 'X'])
1378 Namespace(foo=None, one='X')
1379
1380 >>> # negative number options present, so -2 is an option
1381 >>> parser.parse_args(['-2'])
1382 usage: PROG [-h] [-1 ONE] [foo]
1383 PROG: error: no such option: -2
1384
1385 >>> # negative number options present, so both -1s are options
1386 >>> parser.parse_args(['-1', '-1'])
1387 usage: PROG [-h] [-1 ONE] [foo]
1388 PROG: error: argument -1: expected one argument
1389
Éric Araujo67719bd2011-08-19 02:00:07 +02001390If you have positional arguments that must begin with ``-`` and don't look
Benjamin Petersona39e9662010-03-02 22:05:59 +00001391like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001392:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1393argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001394
1395 >>> parser.parse_args(['--', '-f'])
1396 Namespace(foo='-f', one=None)
1397
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001398.. _prefix-matching:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001399
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001400Argument abbreviations (prefix matching)
1401^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001402
Ezio Melottic69313a2011-04-22 01:29:13 +03001403The :meth:`~ArgumentParser.parse_args` method allows long options to be
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001404abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
1405a unique option)::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001406
1407 >>> parser = argparse.ArgumentParser(prog='PROG')
1408 >>> parser.add_argument('-bacon')
1409 >>> parser.add_argument('-badger')
1410 >>> parser.parse_args('-bac MMM'.split())
1411 Namespace(bacon='MMM', badger=None)
1412 >>> parser.parse_args('-bad WOOD'.split())
1413 Namespace(bacon=None, badger='WOOD')
1414 >>> parser.parse_args('-ba BA'.split())
1415 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1416 PROG: error: ambiguous option: -ba could match -badger, -bacon
1417
Benjamin Peterson90c58022010-03-03 01:55:09 +00001418An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001419
1420
1421Beyond ``sys.argv``
1422^^^^^^^^^^^^^^^^^^^
1423
Éric Araujo67719bd2011-08-19 02:00:07 +02001424Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Georg Brandld2decd92010-03-02 22:17:38 +00001425of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001426:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1427interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001428
1429 >>> parser = argparse.ArgumentParser()
1430 >>> parser.add_argument(
1431 ... 'integers', metavar='int', type=int, choices=xrange(10),
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001432 ... nargs='+', help='an integer in the range 0..9')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001433 >>> parser.add_argument(
1434 ... '--sum', dest='accumulate', action='store_const', const=sum,
Serhiy Storchaka12d547a2016-05-10 13:45:32 +03001435 ... default=max, help='sum the integers (default: find the max)')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001436 >>> parser.parse_args(['1', '2', '3', '4'])
1437 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
Martin Panter11cc5132016-04-26 11:33:46 +00001438 >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001439 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1440
1441
Steven Bethard3f69a052011-03-26 19:59:02 +01001442The Namespace object
1443^^^^^^^^^^^^^^^^^^^^
1444
Éric Araujof0d44bc2011-07-29 17:59:17 +02001445.. class:: Namespace
1446
1447 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1448 an object holding attributes and return it.
1449
1450This class is deliberately simple, just an :class:`object` subclass with a
1451readable string representation. If you prefer to have dict-like view of the
1452attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001453
1454 >>> parser = argparse.ArgumentParser()
1455 >>> parser.add_argument('--foo')
1456 >>> args = parser.parse_args(['--foo', 'BAR'])
1457 >>> vars(args)
1458 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001459
Benjamin Peterson90c58022010-03-03 01:55:09 +00001460It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001461already existing object, rather than a new :class:`Namespace` object. This can
1462be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001463
1464 >>> class C(object):
1465 ... pass
1466 ...
1467 >>> c = C()
1468 >>> parser = argparse.ArgumentParser()
1469 >>> parser.add_argument('--foo')
1470 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1471 >>> c.foo
1472 'BAR'
1473
1474
1475Other utilities
1476---------------
1477
1478Sub-commands
1479^^^^^^^^^^^^
1480
Georg Brandl1f94b262013-10-06 18:51:39 +02001481.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1482 [parser_class], [action], \
1483 [option_string], [dest], [help], \
1484 [metavar])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001485
Benjamin Peterson90c58022010-03-03 01:55:09 +00001486 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001487 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001488 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001489 this way can be a particularly good idea when a program performs several
1490 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001491 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001492 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti82ee3032012-12-28 01:59:24 +02001493 called with no arguments and returns a special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001494 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1495 command name and any :class:`ArgumentParser` constructor arguments, and
1496 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001497
Georg Brandl1f94b262013-10-06 18:51:39 +02001498 Description of parameters:
1499
1500 * title - title for the sub-parser group in help output; by default
1501 "subcommands" if description is provided, otherwise uses title for
1502 positional arguments
1503
1504 * description - description for the sub-parser group in help output, by
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001505 default ``None``
Georg Brandl1f94b262013-10-06 18:51:39 +02001506
1507 * prog - usage information that will be displayed with sub-command help,
1508 by default the name of the program and any positional arguments before the
1509 subparser argument
1510
1511 * parser_class - class which will be used to create sub-parser instances, by
1512 default the class of the current parser (e.g. ArgumentParser)
1513
Berker Peksag1b6e5382015-01-20 06:55:51 +02001514 * action_ - the basic type of action to be taken when this argument is
1515 encountered at the command line
1516
1517 * dest_ - name of the attribute under which sub-command name will be
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001518 stored; by default ``None`` and no value is stored
Georg Brandl1f94b262013-10-06 18:51:39 +02001519
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001520 * help_ - help for sub-parser group in help output, by default ``None``
Georg Brandl1f94b262013-10-06 18:51:39 +02001521
Berker Peksag1b6e5382015-01-20 06:55:51 +02001522 * metavar_ - string presenting available sub-commands in help; by default it
Serhiy Storchakaad13f332016-10-19 16:29:10 +03001523 is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
Georg Brandl1f94b262013-10-06 18:51:39 +02001524
Benjamin Petersona39e9662010-03-02 22:05:59 +00001525 Some example usage::
1526
1527 >>> # create the top-level parser
1528 >>> parser = argparse.ArgumentParser(prog='PROG')
1529 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1530 >>> subparsers = parser.add_subparsers(help='sub-command help')
1531 >>>
1532 >>> # create the parser for the "a" command
1533 >>> parser_a = subparsers.add_parser('a', help='a help')
1534 >>> parser_a.add_argument('bar', type=int, help='bar help')
1535 >>>
1536 >>> # create the parser for the "b" command
1537 >>> parser_b = subparsers.add_parser('b', help='b help')
1538 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1539 >>>
Éric Araujo67719bd2011-08-19 02:00:07 +02001540 >>> # parse some argument lists
Benjamin Petersona39e9662010-03-02 22:05:59 +00001541 >>> parser.parse_args(['a', '12'])
1542 Namespace(bar=12, foo=False)
1543 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1544 Namespace(baz='Z', foo=True)
1545
1546 Note that the object returned by :meth:`parse_args` will only contain
1547 attributes for the main parser and the subparser that was selected by the
1548 command line (and not any other subparsers). So in the example above, when
Éric Araujo67719bd2011-08-19 02:00:07 +02001549 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1550 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001551 ``baz`` attributes are present.
1552
1553 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001554 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001555 include parent parser or sibling parser messages. (A help message for each
1556 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001557 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001558
1559 ::
1560
1561 >>> parser.parse_args(['--help'])
1562 usage: PROG [-h] [--foo] {a,b} ...
1563
1564 positional arguments:
1565 {a,b} sub-command help
Ezio Melottidc157fc2013-01-12 10:39:45 +02001566 a a help
1567 b b help
Benjamin Petersona39e9662010-03-02 22:05:59 +00001568
1569 optional arguments:
1570 -h, --help show this help message and exit
1571 --foo foo help
1572
1573 >>> parser.parse_args(['a', '--help'])
1574 usage: PROG a [-h] bar
1575
1576 positional arguments:
1577 bar bar help
1578
1579 optional arguments:
1580 -h, --help show this help message and exit
1581
1582 >>> parser.parse_args(['b', '--help'])
1583 usage: PROG b [-h] [--baz {X,Y,Z}]
1584
1585 optional arguments:
1586 -h, --help show this help message and exit
1587 --baz {X,Y,Z} baz help
1588
Georg Brandld2decd92010-03-02 22:17:38 +00001589 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1590 keyword arguments. When either is present, the subparser's commands will
1591 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001592
1593 >>> parser = argparse.ArgumentParser()
1594 >>> subparsers = parser.add_subparsers(title='subcommands',
1595 ... description='valid subcommands',
1596 ... help='additional help')
1597 >>> subparsers.add_parser('foo')
1598 >>> subparsers.add_parser('bar')
1599 >>> parser.parse_args(['-h'])
1600 usage: [-h] {foo,bar} ...
1601
1602 optional arguments:
1603 -h, --help show this help message and exit
1604
1605 subcommands:
1606 valid subcommands
1607
1608 {foo,bar} additional help
1609
1610
Georg Brandld2decd92010-03-02 22:17:38 +00001611 One particularly effective way of handling sub-commands is to combine the use
1612 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1613 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001614 example::
1615
1616 >>> # sub-command functions
1617 >>> def foo(args):
1618 ... print args.x * args.y
1619 ...
1620 >>> def bar(args):
1621 ... print '((%s))' % args.z
1622 ...
1623 >>> # create the top-level parser
1624 >>> parser = argparse.ArgumentParser()
1625 >>> subparsers = parser.add_subparsers()
1626 >>>
1627 >>> # create the parser for the "foo" command
1628 >>> parser_foo = subparsers.add_parser('foo')
1629 >>> parser_foo.add_argument('-x', type=int, default=1)
1630 >>> parser_foo.add_argument('y', type=float)
1631 >>> parser_foo.set_defaults(func=foo)
1632 >>>
1633 >>> # create the parser for the "bar" command
1634 >>> parser_bar = subparsers.add_parser('bar')
1635 >>> parser_bar.add_argument('z')
1636 >>> parser_bar.set_defaults(func=bar)
1637 >>>
1638 >>> # parse the args and call whatever function was selected
1639 >>> args = parser.parse_args('foo 1 -x 2'.split())
1640 >>> args.func(args)
1641 2.0
1642 >>>
1643 >>> # parse the args and call whatever function was selected
1644 >>> args = parser.parse_args('bar XYZYX'.split())
1645 >>> args.func(args)
1646 ((XYZYX))
1647
Éric Araujobb42f5e2012-02-20 02:08:01 +01001648 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson90c58022010-03-03 01:55:09 +00001649 appropriate function after argument parsing is complete. Associating
1650 functions with actions like this is typically the easiest way to handle the
1651 different actions for each of your subparsers. However, if it is necessary
1652 to check the name of the subparser that was invoked, the ``dest`` keyword
1653 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001654
1655 >>> parser = argparse.ArgumentParser()
1656 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1657 >>> subparser1 = subparsers.add_parser('1')
1658 >>> subparser1.add_argument('-x')
1659 >>> subparser2 = subparsers.add_parser('2')
1660 >>> subparser2.add_argument('y')
1661 >>> parser.parse_args(['2', 'frobble'])
1662 Namespace(subparser_name='2', y='frobble')
1663
1664
1665FileType objects
1666^^^^^^^^^^^^^^^^
1667
1668.. class:: FileType(mode='r', bufsize=None)
1669
1670 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001671 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujo67719bd2011-08-19 02:00:07 +02001672 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujobb42f5e2012-02-20 02:08:01 +01001673 with the requested modes and buffer sizes::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001674
Éric Araujobb42f5e2012-02-20 02:08:01 +01001675 >>> parser = argparse.ArgumentParser()
1676 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1677 >>> parser.parse_args(['--output', 'out'])
1678 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001679
1680 FileType objects understand the pseudo-argument ``'-'`` and automatically
1681 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujobb42f5e2012-02-20 02:08:01 +01001682 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001683
Éric Araujobb42f5e2012-02-20 02:08:01 +01001684 >>> parser = argparse.ArgumentParser()
1685 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1686 >>> parser.parse_args(['-'])
1687 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001688
1689
1690Argument groups
1691^^^^^^^^^^^^^^^
1692
Georg Brandlb8d0e362010-11-26 07:53:50 +00001693.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001694
Benjamin Peterson90c58022010-03-03 01:55:09 +00001695 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001696 "positional arguments" and "optional arguments" when displaying help
1697 messages. When there is a better conceptual grouping of arguments than this
1698 default one, appropriate groups can be created using the
1699 :meth:`add_argument_group` method::
1700
1701 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1702 >>> group = parser.add_argument_group('group')
1703 >>> group.add_argument('--foo', help='foo help')
1704 >>> group.add_argument('bar', help='bar help')
1705 >>> parser.print_help()
1706 usage: PROG [--foo FOO] bar
1707
1708 group:
1709 bar bar help
1710 --foo FOO foo help
1711
1712 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001713 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1714 :class:`ArgumentParser`. When an argument is added to the group, the parser
1715 treats it just like a normal argument, but displays the argument in a
1716 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001717 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001718 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001719
1720 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1721 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1722 >>> group1.add_argument('foo', help='foo help')
1723 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1724 >>> group2.add_argument('--bar', help='bar help')
1725 >>> parser.print_help()
1726 usage: PROG [--bar BAR] foo
1727
1728 group1:
1729 group1 description
1730
1731 foo foo help
1732
1733 group2:
1734 group2 description
1735
1736 --bar BAR bar help
1737
Sandro Tosi48a88952012-03-26 19:35:52 +02001738 Note that any arguments not in your user-defined groups will end up back
1739 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001740
1741
1742Mutual exclusion
1743^^^^^^^^^^^^^^^^
1744
Georg Brandle3005462013-10-06 13:09:59 +02001745.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001746
Ezio Melotti01b600c2011-04-21 16:12:17 +03001747 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1748 one of the arguments in the mutually exclusive group was present on the
1749 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001750
1751 >>> parser = argparse.ArgumentParser(prog='PROG')
1752 >>> group = parser.add_mutually_exclusive_group()
1753 >>> group.add_argument('--foo', action='store_true')
1754 >>> group.add_argument('--bar', action='store_false')
1755 >>> parser.parse_args(['--foo'])
1756 Namespace(bar=True, foo=True)
1757 >>> parser.parse_args(['--bar'])
1758 Namespace(bar=False, foo=False)
1759 >>> parser.parse_args(['--foo', '--bar'])
1760 usage: PROG [-h] [--foo | --bar]
1761 PROG: error: argument --bar: not allowed with argument --foo
1762
Georg Brandlb8d0e362010-11-26 07:53:50 +00001763 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001764 argument, to indicate that at least one of the mutually exclusive arguments
1765 is required::
1766
1767 >>> parser = argparse.ArgumentParser(prog='PROG')
1768 >>> group = parser.add_mutually_exclusive_group(required=True)
1769 >>> group.add_argument('--foo', action='store_true')
1770 >>> group.add_argument('--bar', action='store_false')
1771 >>> parser.parse_args([])
1772 usage: PROG [-h] (--foo | --bar)
1773 PROG: error: one of the arguments --foo --bar is required
1774
1775 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001776 *title* and *description* arguments of
1777 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001778
1779
1780Parser defaults
1781^^^^^^^^^^^^^^^
1782
Benjamin Peterson90c58022010-03-03 01:55:09 +00001783.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001784
Georg Brandld2decd92010-03-02 22:17:38 +00001785 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujo67719bd2011-08-19 02:00:07 +02001786 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001787 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001788 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001789 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001790
1791 >>> parser = argparse.ArgumentParser()
1792 >>> parser.add_argument('foo', type=int)
1793 >>> parser.set_defaults(bar=42, baz='badger')
1794 >>> parser.parse_args(['736'])
1795 Namespace(bar=42, baz='badger', foo=736)
1796
Benjamin Peterson90c58022010-03-03 01:55:09 +00001797 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001798
1799 >>> parser = argparse.ArgumentParser()
1800 >>> parser.add_argument('--foo', default='bar')
1801 >>> parser.set_defaults(foo='spam')
1802 >>> parser.parse_args([])
1803 Namespace(foo='spam')
1804
Benjamin Peterson90c58022010-03-03 01:55:09 +00001805 Parser-level defaults can be particularly useful when working with multiple
1806 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1807 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001808
Benjamin Peterson90c58022010-03-03 01:55:09 +00001809.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001810
1811 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001812 :meth:`~ArgumentParser.add_argument` or by
1813 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001814
1815 >>> parser = argparse.ArgumentParser()
1816 >>> parser.add_argument('--foo', default='badger')
1817 >>> parser.get_default('foo')
1818 'badger'
1819
1820
1821Printing help
1822^^^^^^^^^^^^^
1823
Ezio Melottic69313a2011-04-22 01:29:13 +03001824In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1825care of formatting and printing any usage or error messages. However, several
1826formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001827
Georg Brandlb8d0e362010-11-26 07:53:50 +00001828.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001829
1830 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001831 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001832 assumed.
1833
Georg Brandlb8d0e362010-11-26 07:53:50 +00001834.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001835
1836 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001837 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001838 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001839
1840There are also variants of these methods that simply return a string instead of
1841printing it:
1842
Georg Brandlb8d0e362010-11-26 07:53:50 +00001843.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001844
1845 Return a string containing a brief description of how the
1846 :class:`ArgumentParser` should be invoked on the command line.
1847
Georg Brandlb8d0e362010-11-26 07:53:50 +00001848.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001849
1850 Return a string containing a help message, including the program usage and
1851 information about the arguments registered with the :class:`ArgumentParser`.
1852
1853
Benjamin Petersona39e9662010-03-02 22:05:59 +00001854Partial parsing
1855^^^^^^^^^^^^^^^
1856
Georg Brandlb8d0e362010-11-26 07:53:50 +00001857.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001858
Ezio Melotti12125822011-04-16 23:04:51 +03001859Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001860the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001861:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001862:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1863extra arguments are present. Instead, it returns a two item tuple containing
1864the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001865
1866::
1867
1868 >>> parser = argparse.ArgumentParser()
1869 >>> parser.add_argument('--foo', action='store_true')
1870 >>> parser.add_argument('bar')
1871 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1872 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1873
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001874.. warning::
1875 :ref:`Prefix matching <prefix-matching>` rules apply to
1876 :meth:`parse_known_args`. The parser may consume an option even if it's just
1877 a prefix of one of its known options, instead of leaving it in the remaining
1878 arguments list.
1879
Benjamin Petersona39e9662010-03-02 22:05:59 +00001880
1881Customizing file parsing
1882^^^^^^^^^^^^^^^^^^^^^^^^
1883
Benjamin Peterson90c58022010-03-03 01:55:09 +00001884.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001885
Georg Brandlb8d0e362010-11-26 07:53:50 +00001886 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001887 keyword argument to the :class:`ArgumentParser` constructor) are read one
Donald Stufft5db0b332014-05-20 12:58:38 -04001888 argument per line. :meth:`convert_arg_line_to_args` can be overridden for
Benjamin Peterson90c58022010-03-03 01:55:09 +00001889 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001890
Georg Brandlb8d0e362010-11-26 07:53:50 +00001891 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001892 the argument file. It returns a list of arguments parsed from this string.
1893 The method is called once per line read from the argument file, in order.
1894
Georg Brandld2decd92010-03-02 22:17:38 +00001895 A useful override of this method is one that treats each space-separated word
1896 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001897
1898 def convert_arg_line_to_args(self, arg_line):
Berker Peksag31200ff2015-04-26 12:12:45 +03001899 return arg_line.split()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001900
1901
Georg Brandlb8d0e362010-11-26 07:53:50 +00001902Exiting methods
1903^^^^^^^^^^^^^^^
1904
1905.. method:: ArgumentParser.exit(status=0, message=None)
1906
1907 This method terminates the program, exiting with the specified *status*
1908 and, if given, it prints a *message* before that.
1909
1910.. method:: ArgumentParser.error(message)
1911
1912 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001913 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001914
1915
Georg Brandl58df6792010-07-03 10:25:47 +00001916.. _argparse-from-optparse:
1917
Benjamin Petersona39e9662010-03-02 22:05:59 +00001918Upgrading optparse code
1919-----------------------
1920
Ezio Melottic69313a2011-04-22 01:29:13 +03001921Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001922with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1923transparently, particularly with the changes required to support the new
1924``nargs=`` specifiers and better usage messages. When most everything in
1925:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1926longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001927
Berker Peksag12f05322014-09-26 15:39:05 +03001928The :mod:`argparse` module improves on the standard library :mod:`optparse`
1929module in a number of ways including:
1930
1931* Handling positional arguments.
1932* Supporting sub-commands.
1933* Allowing alternative option prefixes like ``+`` and ``/``.
1934* Handling zero-or-more and one-or-more style arguments.
1935* Producing more informative usage messages.
1936* Providing a much simpler interface for custom ``type`` and ``action``.
1937
Ezio Melotti01b600c2011-04-21 16:12:17 +03001938A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001939
Ezio Melottic69313a2011-04-22 01:29:13 +03001940* Replace all :meth:`optparse.OptionParser.add_option` calls with
1941 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001942
R David Murray5080cad2012-03-30 18:09:07 -04001943* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001944 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5080cad2012-03-30 18:09:07 -04001945 calls for the positional arguments. Keep in mind that what was previously
1946 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001947
1948* Replace callback actions and the ``callback_*`` keyword arguments with
1949 ``type`` or ``action`` arguments.
1950
1951* Replace string names for ``type`` keyword arguments with the corresponding
1952 type objects (e.g. int, float, complex, etc).
1953
Benjamin Peterson90c58022010-03-03 01:55:09 +00001954* Replace :class:`optparse.Values` with :class:`Namespace` and
1955 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1956 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001957
Georg Brandld2decd92010-03-02 22:17:38 +00001958* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001959 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001960 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001961
1962* Replace the OptionParser constructor ``version`` argument with a call to
Martin Panter4ed35fc2015-10-10 10:52:35 +00001963 ``parser.add_argument('--version', action='version', version='<the version>')``.