blob: fd75cfeb4cbe85e97d21bdf976440659c0ae1884 [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='+',
38 help='an integer for the accumulator')
39 parser.add_argument('--sum', dest='accumulate', action='store_const',
40 const=sum, default=max,
41 help='sum the integers (default: find the max)')
42
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
47be run at the command line and provides useful help messages::
48
Georg Brandl9f572782013-10-06 19:33:56 +020049 $ python prog.py -h
Benjamin Petersona39e9662010-03-02 22:05:59 +000050 usage: prog.py [-h] [--sum] N [N ...]
51
52 Process some integers.
53
54 positional arguments:
55 N an integer for the accumulator
56
57 optional arguments:
58 -h, --help show this help message and exit
59 --sum sum the integers (default: find the max)
60
61When run with the appropriate arguments, it prints either the sum or the max of
62the command-line integers::
63
Georg Brandl9f572782013-10-06 19:33:56 +020064 $ python prog.py 1 2 3 4
Benjamin Petersona39e9662010-03-02 22:05:59 +000065 4
66
Georg Brandl9f572782013-10-06 19:33:56 +020067 $ python prog.py 1 2 3 4 --sum
Benjamin Petersona39e9662010-03-02 22:05:59 +000068 10
69
70If invalid arguments are passed in, it will issue an error::
71
Georg Brandl9f572782013-10-06 19:33:56 +020072 $ python prog.py a b c
Benjamin Petersona39e9662010-03-02 22:05:59 +000073 usage: prog.py [-h] [--sum] N [N ...]
74 prog.py: error: argument N: invalid int value: 'a'
75
76The following sections walk you through this example.
77
Georg Brandlb8d0e362010-11-26 07:53:50 +000078
Benjamin Petersona39e9662010-03-02 22:05:59 +000079Creating a parser
80^^^^^^^^^^^^^^^^^
81
Benjamin Petersonac80c152010-03-03 21:28:25 +000082The first step in using the :mod:`argparse` is creating an
Benjamin Peterson90c58022010-03-03 01:55:09 +000083:class:`ArgumentParser` object::
Benjamin Petersona39e9662010-03-02 22:05:59 +000084
85 >>> parser = argparse.ArgumentParser(description='Process some integers.')
86
87The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotti2eab88e2011-04-21 15:26:46 +030088parse the command line into Python data types.
Benjamin Petersona39e9662010-03-02 22:05:59 +000089
90
91Adding arguments
92^^^^^^^^^^^^^^^^
93
Benjamin Peterson90c58022010-03-03 01:55:09 +000094Filling an :class:`ArgumentParser` with information about program arguments is
95done by making calls to the :meth:`~ArgumentParser.add_argument` method.
96Generally, these calls tell the :class:`ArgumentParser` how to take the strings
97on the command line and turn them into objects. This information is stored and
98used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +000099
100 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
101 ... help='an integer for the accumulator')
102 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
103 ... const=sum, default=max,
104 ... help='sum the integers (default: find the max)')
105
Ezio Melottic69313a2011-04-22 01:29:13 +0300106Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Georg Brandld2decd92010-03-02 22:17:38 +0000107two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
108will be a list of one or more ints, and the ``accumulate`` attribute will be
109either the :func:`sum` function, if ``--sum`` was specified at the command line,
110or the :func:`max` function if it was not.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000111
Georg Brandlb8d0e362010-11-26 07:53:50 +0000112
Benjamin Petersona39e9662010-03-02 22:05:59 +0000113Parsing arguments
114^^^^^^^^^^^^^^^^^
115
Éric Araujo67719bd2011-08-19 02:00:07 +0200116:class:`ArgumentParser` parses arguments through the
Ezio Melotti12125822011-04-16 23:04:51 +0300117:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujo67719bd2011-08-19 02:00:07 +0200118convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujof0d44bc2011-07-29 17:59:17 +0200119In most cases, this means a simple :class:`Namespace` object will be built up from
Ezio Melotti12125822011-04-16 23:04:51 +0300120attributes parsed out of the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000121
122 >>> parser.parse_args(['--sum', '7', '-1', '42'])
123 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
124
Benjamin Peterson90c58022010-03-03 01:55:09 +0000125In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
126arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujo67719bd2011-08-19 02:00:07 +0200127command-line arguments from :data:`sys.argv`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000128
129
130ArgumentParser objects
131----------------------
132
Ezio Melottied3f5902012-09-14 06:48:32 +0300133.. class:: ArgumentParser(prog=None, usage=None, description=None, \
134 epilog=None, parents=[], \
135 formatter_class=argparse.HelpFormatter, \
136 prefix_chars='-', fromfile_prefix_chars=None, \
137 argument_default=None, conflict_handler='error', \
138 add_help=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000139
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300140 Create a new :class:`ArgumentParser` object. All parameters should be passed
141 as keyword arguments. Each parameter has its own more detailed description
142 below, but in short they are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000143
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300144 * prog_ - The name of the program (default: ``sys.argv[0]``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000145
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300146 * usage_ - The string describing the program usage (default: generated from
147 arguments added to parser)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000148
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300149 * description_ - Text to display before the argument help (default: none)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000150
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300151 * epilog_ - Text to display after the argument help (default: none)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000152
Benjamin Peterson90c58022010-03-03 01:55:09 +0000153 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300154 also be included
Benjamin Petersona39e9662010-03-02 22:05:59 +0000155
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300156 * formatter_class_ - A class for customizing the help output
157
158 * prefix_chars_ - The set of characters that prefix optional arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000159 (default: '-')
160
161 * fromfile_prefix_chars_ - The set of characters that prefix files from
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300162 which additional arguments should be read (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000163
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300164 * argument_default_ - The global default value for arguments
165 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000166
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300167 * conflict_handler_ - The strategy for resolving conflicting optionals
168 (usually unnecessary)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000169
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300170 * add_help_ - Add a -h/--help option to the parser (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000171
Benjamin Peterson90c58022010-03-03 01:55:09 +0000172The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000173
174
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300175prog
176^^^^
177
178By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
179how to display the name of the program in help messages. This default is almost
180always desirable because it will make the help messages match how the program was
181invoked on the command line. For example, consider a file named
182``myprogram.py`` with the following code::
183
184 import argparse
185 parser = argparse.ArgumentParser()
186 parser.add_argument('--foo', help='foo help')
187 args = parser.parse_args()
188
189The help for this program will display ``myprogram.py`` as the program name
190(regardless of where the program was invoked from)::
191
192 $ python myprogram.py --help
193 usage: myprogram.py [-h] [--foo FOO]
194
195 optional arguments:
196 -h, --help show this help message and exit
197 --foo FOO foo help
198 $ cd ..
199 $ python subdir\myprogram.py --help
200 usage: myprogram.py [-h] [--foo FOO]
201
202 optional arguments:
203 -h, --help show this help message and exit
204 --foo FOO foo help
205
206To change this default behavior, another value can be supplied using the
207``prog=`` argument to :class:`ArgumentParser`::
208
209 >>> parser = argparse.ArgumentParser(prog='myprogram')
210 >>> parser.print_help()
211 usage: myprogram [-h]
212
213 optional arguments:
214 -h, --help show this help message and exit
215
216Note that the program name, whether determined from ``sys.argv[0]`` or from the
217``prog=`` argument, is available to help messages using the ``%(prog)s`` format
218specifier.
219
220::
221
222 >>> parser = argparse.ArgumentParser(prog='myprogram')
223 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
224 >>> parser.print_help()
225 usage: myprogram [-h] [--foo FOO]
226
227 optional arguments:
228 -h, --help show this help message and exit
229 --foo FOO foo of the myprogram program
230
231
232usage
233^^^^^
234
235By default, :class:`ArgumentParser` calculates the usage message from the
236arguments it contains::
237
238 >>> parser = argparse.ArgumentParser(prog='PROG')
239 >>> parser.add_argument('--foo', nargs='?', help='foo help')
240 >>> parser.add_argument('bar', nargs='+', help='bar help')
241 >>> parser.print_help()
242 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
243
244 positional arguments:
245 bar bar help
246
247 optional arguments:
248 -h, --help show this help message and exit
249 --foo [FOO] foo help
250
251The default message can be overridden with the ``usage=`` keyword argument::
252
253 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
254 >>> parser.add_argument('--foo', nargs='?', help='foo help')
255 >>> parser.add_argument('bar', nargs='+', help='bar help')
256 >>> parser.print_help()
257 usage: PROG [options]
258
259 positional arguments:
260 bar bar help
261
262 optional arguments:
263 -h, --help show this help message and exit
264 --foo [FOO] foo help
265
266The ``%(prog)s`` format specifier is available to fill in the program name in
267your usage messages.
268
269
Benjamin Petersona39e9662010-03-02 22:05:59 +0000270description
271^^^^^^^^^^^
272
Benjamin Peterson90c58022010-03-03 01:55:09 +0000273Most calls to the :class:`ArgumentParser` constructor will use the
274``description=`` keyword argument. This argument gives a brief description of
275what the program does and how it works. In help messages, the description is
276displayed between the command-line usage string and the help messages for the
277various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000278
279 >>> parser = argparse.ArgumentParser(description='A foo that bars')
280 >>> parser.print_help()
281 usage: argparse.py [-h]
282
283 A foo that bars
284
285 optional arguments:
286 -h, --help show this help message and exit
287
288By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000289given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000290
291
292epilog
293^^^^^^
294
295Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000296description of the arguments. Such text can be specified using the ``epilog=``
297argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000298
299 >>> parser = argparse.ArgumentParser(
300 ... description='A foo that bars',
301 ... epilog="And that's how you'd foo a bar")
302 >>> parser.print_help()
303 usage: argparse.py [-h]
304
305 A foo that bars
306
307 optional arguments:
308 -h, --help show this help message and exit
309
310 And that's how you'd foo a bar
311
312As with the description_ argument, the ``epilog=`` text is by default
313line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000314argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000315
316
Benjamin Petersona39e9662010-03-02 22:05:59 +0000317parents
318^^^^^^^
319
320Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000321repeating the definitions of these arguments, a single parser with all the
322shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
323can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
324objects, collects all the positional and optional actions from them, and adds
325these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000326
327 >>> parent_parser = argparse.ArgumentParser(add_help=False)
328 >>> parent_parser.add_argument('--parent', type=int)
329
330 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
331 >>> foo_parser.add_argument('foo')
332 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
333 Namespace(foo='XXX', parent=2)
334
335 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
336 >>> bar_parser.add_argument('--bar')
337 >>> bar_parser.parse_args(['--bar', 'YYY'])
338 Namespace(bar='YYY', parent=None)
339
Georg Brandld2decd92010-03-02 22:17:38 +0000340Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000341:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
342and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000343
Steven Bethard5e0062d2011-03-26 21:50:38 +0100344.. note::
345 You must fully initialize the parsers before passing them via ``parents=``.
346 If you change the parent parsers after the child parser, those changes will
347 not be reflected in the child.
348
Benjamin Petersona39e9662010-03-02 22:05:59 +0000349
350formatter_class
351^^^^^^^^^^^^^^^
352
Benjamin Peterson90c58022010-03-03 01:55:09 +0000353:class:`ArgumentParser` objects allow the help formatting to be customized by
354specifying an alternate formatting class. Currently, there are three such
Ezio Melottic69313a2011-04-22 01:29:13 +0300355classes:
356
357.. class:: RawDescriptionHelpFormatter
358 RawTextHelpFormatter
359 ArgumentDefaultsHelpFormatter
360
361The first two allow more control over how textual descriptions are displayed,
362while the last automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000363
Benjamin Peterson90c58022010-03-03 01:55:09 +0000364By default, :class:`ArgumentParser` objects line-wrap the description_ and
365epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000366
367 >>> parser = argparse.ArgumentParser(
368 ... prog='PROG',
369 ... description='''this description
370 ... was indented weird
371 ... but that is okay''',
372 ... epilog='''
373 ... likewise for this epilog whose whitespace will
374 ... be cleaned up and whose words will be wrapped
375 ... across a couple lines''')
376 >>> parser.print_help()
377 usage: PROG [-h]
378
379 this description was indented weird but that is okay
380
381 optional arguments:
382 -h, --help show this help message and exit
383
384 likewise for this epilog whose whitespace will be cleaned up and whose words
385 will be wrapped across a couple lines
386
Éric Araujo67719bd2011-08-19 02:00:07 +0200387Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000388indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000389should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000390
391 >>> parser = argparse.ArgumentParser(
392 ... prog='PROG',
393 ... formatter_class=argparse.RawDescriptionHelpFormatter,
394 ... description=textwrap.dedent('''\
395 ... Please do not mess up this text!
396 ... --------------------------------
397 ... I have indented it
398 ... exactly the way
399 ... I want it
400 ... '''))
401 >>> parser.print_help()
402 usage: PROG [-h]
403
404 Please do not mess up this text!
405 --------------------------------
406 I have indented it
407 exactly the way
408 I want it
409
410 optional arguments:
411 -h, --help show this help message and exit
412
Éric Araujo67719bd2011-08-19 02:00:07 +0200413:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson90c58022010-03-03 01:55:09 +0000414including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000415
Benjamin Peterson90c58022010-03-03 01:55:09 +0000416The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000417will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000418
419 >>> parser = argparse.ArgumentParser(
420 ... prog='PROG',
421 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
422 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
423 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
424 >>> parser.print_help()
425 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
426
427 positional arguments:
428 bar BAR! (default: [1, 2, 3])
429
430 optional arguments:
431 -h, --help show this help message and exit
432 --foo FOO FOO! (default: 42)
433
434
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300435prefix_chars
436^^^^^^^^^^^^
437
438Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
439Parsers that need to support different or additional prefix
440characters, e.g. for options
441like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
442to the ArgumentParser constructor::
443
444 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
445 >>> parser.add_argument('+f')
446 >>> parser.add_argument('++bar')
447 >>> parser.parse_args('+f X ++bar Y'.split())
448 Namespace(bar='Y', f='X')
449
450The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
451characters that does not include ``-`` will cause ``-f/--foo`` options to be
452disallowed.
453
454
455fromfile_prefix_chars
456^^^^^^^^^^^^^^^^^^^^^
457
458Sometimes, for example when dealing with a particularly long argument lists, it
459may make sense to keep the list of arguments in a file rather than typing it out
460at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
461:class:`ArgumentParser` constructor, then arguments that start with any of the
462specified characters will be treated as files, and will be replaced by the
463arguments they contain. For example::
464
465 >>> with open('args.txt', 'w') as fp:
466 ... fp.write('-f\nbar')
467 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
468 >>> parser.add_argument('-f')
469 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
470 Namespace(f='bar')
471
472Arguments read from a file must by default be one per line (but see also
473:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
474were in the same place as the original file referencing argument on the command
475line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
476is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
477
478The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
479arguments will never be treated as file references.
480
481
482argument_default
483^^^^^^^^^^^^^^^^
484
485Generally, argument defaults are specified either by passing a default to
486:meth:`~ArgumentParser.add_argument` or by calling the
487:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
488pairs. Sometimes however, it may be useful to specify a single parser-wide
489default for arguments. This can be accomplished by passing the
490``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
491to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
492calls, we supply ``argument_default=SUPPRESS``::
493
494 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
495 >>> parser.add_argument('--foo')
496 >>> parser.add_argument('bar', nargs='?')
497 >>> parser.parse_args(['--foo', '1', 'BAR'])
498 Namespace(bar='BAR', foo='1')
499 >>> parser.parse_args([])
500 Namespace()
501
502
Benjamin Petersona39e9662010-03-02 22:05:59 +0000503conflict_handler
504^^^^^^^^^^^^^^^^
505
Benjamin Peterson90c58022010-03-03 01:55:09 +0000506:class:`ArgumentParser` objects do not allow two actions with the same option
507string. By default, :class:`ArgumentParser` objects raises an exception if an
508attempt is made to create an argument with an option string that is already in
509use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000510
511 >>> parser = argparse.ArgumentParser(prog='PROG')
512 >>> parser.add_argument('-f', '--foo', help='old foo help')
513 >>> parser.add_argument('--foo', help='new foo help')
514 Traceback (most recent call last):
515 ..
516 ArgumentError: argument --foo: conflicting option string(s): --foo
517
518Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000519older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000520``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000521:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000522
523 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
524 >>> parser.add_argument('-f', '--foo', help='old foo help')
525 >>> parser.add_argument('--foo', help='new foo help')
526 >>> parser.print_help()
527 usage: PROG [-h] [-f FOO] [--foo FOO]
528
529 optional arguments:
530 -h, --help show this help message and exit
531 -f FOO old foo help
532 --foo FOO new foo help
533
Benjamin Peterson90c58022010-03-03 01:55:09 +0000534Note that :class:`ArgumentParser` objects only remove an action if all of its
535option strings are overridden. So, in the example above, the old ``-f/--foo``
536action is retained as the ``-f`` action, because only the ``--foo`` option
537string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000538
539
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300540add_help
541^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +0000542
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300543By default, ArgumentParser objects add an option which simply displays
544the parser's help message. For example, consider a file named
545``myprogram.py`` containing the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000546
547 import argparse
548 parser = argparse.ArgumentParser()
549 parser.add_argument('--foo', help='foo help')
550 args = parser.parse_args()
551
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300552If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
553help will be printed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000554
555 $ python myprogram.py --help
556 usage: myprogram.py [-h] [--foo FOO]
557
558 optional arguments:
559 -h, --help show this help message and exit
560 --foo FOO foo help
Benjamin Petersona39e9662010-03-02 22:05:59 +0000561
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300562Occasionally, it may be useful to disable the addition of this help option.
563This can be achieved by passing ``False`` as the ``add_help=`` argument to
564:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000565
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300566 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
567 >>> parser.add_argument('--foo', help='foo help')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000568 >>> parser.print_help()
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300569 usage: PROG [--foo FOO]
Benjamin Petersona39e9662010-03-02 22:05:59 +0000570
571 optional arguments:
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300572 --foo FOO foo help
Benjamin Petersona39e9662010-03-02 22:05:59 +0000573
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300574The help option is typically ``-h/--help``. The exception to this is
575if the ``prefix_chars=`` is specified and does not include ``-``, in
576which case ``-h`` and ``--help`` are not valid options. In
577this case, the first character in ``prefix_chars`` is used to prefix
578the help options::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000579
Andrew Svetlovaff9cef2013-04-07 14:45:37 +0300580 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000581 >>> parser.print_help()
Georg Brandl2b385822013-10-06 09:50:36 +0200582 usage: PROG [+h]
Benjamin Petersona39e9662010-03-02 22:05:59 +0000583
584 optional arguments:
Georg Brandl2b385822013-10-06 09:50:36 +0200585 +h, ++help show this help message and exit
Benjamin Petersona39e9662010-03-02 22:05:59 +0000586
587
588The add_argument() method
589-------------------------
590
Éric Araujobb42f5e2012-02-20 02:08:01 +0100591.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
592 [const], [default], [type], [choices], [required], \
593 [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000594
Ezio Melotti12125822011-04-16 23:04:51 +0300595 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000596 has its own more detailed description below, but in short they are:
597
598 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300599 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000600
601 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300602 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000603
604 * nargs_ - The number of command-line arguments that should be consumed.
605
606 * const_ - A constant value required by some action_ and nargs_ selections.
607
608 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300609 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000610
Ezio Melotti12125822011-04-16 23:04:51 +0300611 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000612
613 * choices_ - A container of the allowable values for the argument.
614
615 * required_ - Whether or not the command-line option may be omitted
616 (optionals only).
617
618 * help_ - A brief description of what the argument does.
619
620 * metavar_ - A name for the argument in usage messages.
621
622 * dest_ - The name of the attribute to be added to the object returned by
623 :meth:`parse_args`.
624
Benjamin Peterson90c58022010-03-03 01:55:09 +0000625The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000626
Georg Brandlb8d0e362010-11-26 07:53:50 +0000627
Benjamin Petersona39e9662010-03-02 22:05:59 +0000628name or flags
629^^^^^^^^^^^^^
630
Ezio Melottic69313a2011-04-22 01:29:13 +0300631The :meth:`~ArgumentParser.add_argument` method must know whether an optional
632argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
633filenames, is expected. The first arguments passed to
634:meth:`~ArgumentParser.add_argument` must therefore be either a series of
635flags, or a simple argument name. For example, an optional argument could
636be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000637
638 >>> parser.add_argument('-f', '--foo')
639
640while a positional argument could be created like::
641
642 >>> parser.add_argument('bar')
643
Ezio Melottic69313a2011-04-22 01:29:13 +0300644When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
645identified by the ``-`` prefix, and the remaining arguments will be assumed to
646be positional::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000647
648 >>> parser = argparse.ArgumentParser(prog='PROG')
649 >>> parser.add_argument('-f', '--foo')
650 >>> parser.add_argument('bar')
651 >>> parser.parse_args(['BAR'])
652 Namespace(bar='BAR', foo=None)
653 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
654 Namespace(bar='BAR', foo='FOO')
655 >>> parser.parse_args(['--foo', 'FOO'])
656 usage: PROG [-h] [-f FOO] bar
657 PROG: error: too few arguments
658
Georg Brandlb8d0e362010-11-26 07:53:50 +0000659
Benjamin Petersona39e9662010-03-02 22:05:59 +0000660action
661^^^^^^
662
Éric Araujo67719bd2011-08-19 02:00:07 +0200663:class:`ArgumentParser` objects associate command-line arguments with actions. These
664actions can do just about anything with the command-line arguments associated with
Benjamin Petersona39e9662010-03-02 22:05:59 +0000665them, though most actions simply add an attribute to the object returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300666:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombs2c34fb52011-12-13 23:36:45 -0500667how the command-line arguments should be handled. The supplied actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000668
Georg Brandld2decd92010-03-02 22:17:38 +0000669* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300670 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000671
672 >>> parser = argparse.ArgumentParser()
673 >>> parser.add_argument('--foo')
674 >>> parser.parse_args('--foo 1'.split())
675 Namespace(foo='1')
676
677* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti310619c2011-04-21 23:06:48 +0300678 argument. (Note that the const_ keyword argument defaults to the rather
679 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
680 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000681
682 >>> parser = argparse.ArgumentParser()
683 >>> parser.add_argument('--foo', action='store_const', const=42)
684 >>> parser.parse_args('--foo'.split())
685 Namespace(foo=42)
686
Raymond Hettinger421467f2011-11-20 11:05:23 -0800687* ``'store_true'`` and ``'store_false'`` - These are special cases of
688 ``'store_const'`` using for storing the values ``True`` and ``False``
689 respectively. In addition, they create default values of *False* and *True*
690 respectively. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000691
692 >>> parser = argparse.ArgumentParser()
693 >>> parser.add_argument('--foo', action='store_true')
694 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettinger421467f2011-11-20 11:05:23 -0800695 >>> parser.add_argument('--baz', action='store_false')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000696 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettinger421467f2011-11-20 11:05:23 -0800697 Namespace(bar=False, baz=True, foo=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000698
699* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000700 list. This is useful to allow an option to be specified multiple times.
701 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000702
703 >>> parser = argparse.ArgumentParser()
704 >>> parser.add_argument('--foo', action='append')
705 >>> parser.parse_args('--foo 1 --foo 2'.split())
706 Namespace(foo=['1', '2'])
707
708* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000709 the const_ keyword argument to the list. (Note that the const_ keyword
710 argument defaults to ``None``.) The ``'append_const'`` action is typically
711 useful when multiple arguments need to store constants to the same list. For
712 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000713
714 >>> parser = argparse.ArgumentParser()
715 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
716 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
717 >>> parser.parse_args('--str --int'.split())
718 Namespace(types=[<type 'str'>, <type 'int'>])
719
Sandro Tosi8b211fc2012-01-04 23:24:48 +0100720* ``'count'`` - This counts the number of times a keyword argument occurs. For
721 example, this is useful for increasing verbosity levels::
722
723 >>> parser = argparse.ArgumentParser()
724 >>> parser.add_argument('--verbose', '-v', action='count')
725 >>> parser.parse_args('-vvv'.split())
726 Namespace(verbose=3)
727
728* ``'help'`` - This prints a complete help message for all the options in the
729 current parser and then exits. By default a help action is automatically
730 added to the parser. See :class:`ArgumentParser` for details of how the
731 output is created.
732
Benjamin Petersona39e9662010-03-02 22:05:59 +0000733* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melottic69313a2011-04-22 01:29:13 +0300734 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujobb42f5e2012-02-20 02:08:01 +0100735 and exits when invoked::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000736
737 >>> import argparse
738 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000739 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
740 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000741 PROG 2.0
742
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400743You may also specify an arbitrary action by passing an Action subclass or
744other object that implements the same interface. The recommended way to do
Jason R. Coombs2b492032014-08-03 14:54:11 -0400745this is to extend :class:`Action`, overriding the ``__call__`` method
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400746and optionally the ``__init__`` method.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000747
Benjamin Peterson90c58022010-03-03 01:55:09 +0000748An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000749
750 >>> class FooAction(argparse.Action):
Jason R. Coombs69cd3462014-07-20 10:52:46 -0400751 ... def __init__(self, option_strings, dest, nargs=None, **kwargs):
752 ... if nargs is not None:
753 ... raise ValueError("nargs not allowed")
754 ... super(FooAction, self).__init__(option_strings, dest, **kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000755 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000756 ... print '%r %r %r' % (namespace, values, option_string)
757 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000758 ...
759 >>> parser = argparse.ArgumentParser()
760 >>> parser.add_argument('--foo', action=FooAction)
761 >>> parser.add_argument('bar', action=FooAction)
762 >>> args = parser.parse_args('1 --foo 2'.split())
763 Namespace(bar=None, foo=None) '1' None
764 Namespace(bar='1', foo=None) '2' '--foo'
765 >>> args
766 Namespace(bar='1', foo='2')
767
Jason R. Coombs2b492032014-08-03 14:54:11 -0400768For more details, see :class:`Action`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000769
770nargs
771^^^^^
772
773ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000774single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300775different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000776values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000777
Éric Araujobb42f5e2012-02-20 02:08:01 +0100778* ``N`` (an integer). ``N`` arguments from the command line will be gathered
779 together into a list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000780
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000781 >>> parser = argparse.ArgumentParser()
782 >>> parser.add_argument('--foo', nargs=2)
783 >>> parser.add_argument('bar', nargs=1)
784 >>> parser.parse_args('c --foo a b'.split())
785 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000786
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000787 Note that ``nargs=1`` produces a list of one item. This is different from
788 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000789
Éric Araujo67719bd2011-08-19 02:00:07 +0200790* ``'?'``. One argument will be consumed from the command line if possible, and
791 produced as a single item. If no command-line argument is present, the value from
Benjamin Petersona39e9662010-03-02 22:05:59 +0000792 default_ will be produced. Note that for optional arguments, there is an
793 additional case - the option string is present but not followed by a
Éric Araujo67719bd2011-08-19 02:00:07 +0200794 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Petersona39e9662010-03-02 22:05:59 +0000795 examples to illustrate this::
796
Georg Brandld2decd92010-03-02 22:17:38 +0000797 >>> parser = argparse.ArgumentParser()
798 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
799 >>> parser.add_argument('bar', nargs='?', default='d')
800 >>> parser.parse_args('XX --foo YY'.split())
801 Namespace(bar='XX', foo='YY')
802 >>> parser.parse_args('XX --foo'.split())
803 Namespace(bar='XX', foo='c')
804 >>> parser.parse_args(''.split())
805 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000806
Georg Brandld2decd92010-03-02 22:17:38 +0000807 One of the more common uses of ``nargs='?'`` is to allow optional input and
808 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000809
Georg Brandld2decd92010-03-02 22:17:38 +0000810 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000811 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
812 ... default=sys.stdin)
813 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
814 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000815 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000816 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
817 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000818 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000819 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
820 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000821
Éric Araujo67719bd2011-08-19 02:00:07 +0200822* ``'*'``. All command-line arguments present are gathered into a list. Note that
Georg Brandld2decd92010-03-02 22:17:38 +0000823 it generally doesn't make much sense to have more than one positional argument
824 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
825 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000826
Georg Brandld2decd92010-03-02 22:17:38 +0000827 >>> parser = argparse.ArgumentParser()
828 >>> parser.add_argument('--foo', nargs='*')
829 >>> parser.add_argument('--bar', nargs='*')
830 >>> parser.add_argument('baz', nargs='*')
831 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
832 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000833
834* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
835 list. Additionally, an error message will be generated if there wasn't at
Éric Araujo67719bd2011-08-19 02:00:07 +0200836 least one command-line argument present. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000837
Georg Brandld2decd92010-03-02 22:17:38 +0000838 >>> parser = argparse.ArgumentParser(prog='PROG')
839 >>> parser.add_argument('foo', nargs='+')
840 >>> parser.parse_args('a b'.split())
841 Namespace(foo=['a', 'b'])
842 >>> parser.parse_args(''.split())
843 usage: PROG [-h] foo [foo ...]
844 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000845
Sandro Tosicb212272012-01-19 22:22:35 +0100846* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
847 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujobb42f5e2012-02-20 02:08:01 +0100848 to other command line utilities::
Sandro Tosi10f047d2012-01-19 21:59:34 +0100849
850 >>> parser = argparse.ArgumentParser(prog='PROG')
851 >>> parser.add_argument('--foo')
852 >>> parser.add_argument('command')
853 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosicb212272012-01-19 22:22:35 +0100854 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
855 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi10f047d2012-01-19 21:59:34 +0100856
Éric Araujo67719bd2011-08-19 02:00:07 +0200857If the ``nargs`` keyword argument is not provided, the number of arguments consumed
858is determined by the action_. Generally this means a single command-line argument
Benjamin Petersona39e9662010-03-02 22:05:59 +0000859will be consumed and a single item (not a list) will be produced.
860
861
862const
863^^^^^
864
Ezio Melottic69313a2011-04-22 01:29:13 +0300865The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
866constant values that are not read from the command line but are required for
867the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000868
Ezio Melottic69313a2011-04-22 01:29:13 +0300869* When :meth:`~ArgumentParser.add_argument` is called with
870 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujobb42f5e2012-02-20 02:08:01 +0100871 ``const`` value to one of the attributes of the object returned by
872 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000873
Ezio Melottic69313a2011-04-22 01:29:13 +0300874* When :meth:`~ArgumentParser.add_argument` is called with option strings
875 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujo67719bd2011-08-19 02:00:07 +0200876 argument that can be followed by zero or one command-line arguments.
Ezio Melottic69313a2011-04-22 01:29:13 +0300877 When parsing the command line, if the option string is encountered with no
Éric Araujo67719bd2011-08-19 02:00:07 +0200878 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melottic69313a2011-04-22 01:29:13 +0300879 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000880
881The ``const`` keyword argument defaults to ``None``.
882
883
884default
885^^^^^^^
886
887All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300888command line. The ``default`` keyword argument of
889:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujo67719bd2011-08-19 02:00:07 +0200890specifies what value should be used if the command-line argument is not present.
Ezio Melottic69313a2011-04-22 01:29:13 +0300891For optional arguments, the ``default`` value is used when the option string
892was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000893
894 >>> parser = argparse.ArgumentParser()
895 >>> parser.add_argument('--foo', default=42)
896 >>> parser.parse_args('--foo 2'.split())
897 Namespace(foo='2')
898 >>> parser.parse_args(''.split())
899 Namespace(foo=42)
900
Barry Warsaw0dea9362012-09-25 10:32:53 -0400901If the ``default`` value is a string, the parser parses the value as if it
902were a command-line argument. In particular, the parser applies any type_
903conversion argument, if provided, before setting the attribute on the
904:class:`Namespace` return value. Otherwise, the parser uses the value as is::
905
906 >>> parser = argparse.ArgumentParser()
907 >>> parser.add_argument('--length', default='10', type=int)
908 >>> parser.add_argument('--width', default=10.5, type=int)
909 >>> parser.parse_args()
910 Namespace(length=10, width=10.5)
911
Éric Araujo67719bd2011-08-19 02:00:07 +0200912For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
913is used when no command-line argument was present::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000914
915 >>> parser = argparse.ArgumentParser()
916 >>> parser.add_argument('foo', nargs='?', default=42)
917 >>> parser.parse_args('a'.split())
918 Namespace(foo='a')
919 >>> parser.parse_args(''.split())
920 Namespace(foo=42)
921
922
Benjamin Peterson90c58022010-03-03 01:55:09 +0000923Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
924command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000925
926 >>> parser = argparse.ArgumentParser()
927 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
928 >>> parser.parse_args([])
929 Namespace()
930 >>> parser.parse_args(['--foo', '1'])
931 Namespace(foo='1')
932
933
934type
935^^^^
936
Éric Araujo67719bd2011-08-19 02:00:07 +0200937By default, :class:`ArgumentParser` objects read command-line arguments in as simple
938strings. However, quite often the command-line string should instead be
939interpreted as another type, like a :class:`float` or :class:`int`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300940``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujo67719bd2011-08-19 02:00:07 +0200941necessary type-checking and type conversions to be performed. Common built-in
942types and functions can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000943
944 >>> parser = argparse.ArgumentParser()
945 >>> parser.add_argument('foo', type=int)
946 >>> parser.add_argument('bar', type=file)
947 >>> parser.parse_args('2 temp.txt'.split())
948 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
949
Barry Warsaw0dea9362012-09-25 10:32:53 -0400950See the section on the default_ keyword argument for information on when the
951``type`` argument is applied to default arguments.
952
Benjamin Petersona39e9662010-03-02 22:05:59 +0000953To ease the use of various types of files, the argparse module provides the
954factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000955``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000956writable file::
957
958 >>> parser = argparse.ArgumentParser()
959 >>> parser.add_argument('bar', type=argparse.FileType('w'))
960 >>> parser.parse_args(['out.txt'])
961 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
962
Benjamin Peterson90c58022010-03-03 01:55:09 +0000963``type=`` can take any callable that takes a single string argument and returns
Éric Araujo67719bd2011-08-19 02:00:07 +0200964the converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000965
966 >>> def perfect_square(string):
967 ... value = int(string)
968 ... sqrt = math.sqrt(value)
969 ... if sqrt != int(sqrt):
970 ... msg = "%r is not a perfect square" % string
971 ... raise argparse.ArgumentTypeError(msg)
972 ... return value
973 ...
974 >>> parser = argparse.ArgumentParser(prog='PROG')
975 >>> parser.add_argument('foo', type=perfect_square)
976 >>> parser.parse_args('9'.split())
977 Namespace(foo=9)
978 >>> parser.parse_args('7'.split())
979 usage: PROG [-h] foo
980 PROG: error: argument foo: '7' is not a perfect square
981
Benjamin Peterson90c58022010-03-03 01:55:09 +0000982The choices_ keyword argument may be more convenient for type checkers that
983simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000984
985 >>> parser = argparse.ArgumentParser(prog='PROG')
986 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
987 >>> parser.parse_args('7'.split())
988 Namespace(foo=7)
989 >>> parser.parse_args('11'.split())
990 usage: PROG [-h] {5,6,7,8,9}
991 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
992
993See the choices_ section for more details.
994
995
996choices
997^^^^^^^
998
Éric Araujo67719bd2011-08-19 02:00:07 +0200999Some command-line arguments should be selected from a restricted set of values.
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001000These can be handled by passing a container object as the *choices* keyword
Ezio Melottic69313a2011-04-22 01:29:13 +03001001argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001002parsed, argument values will be checked, and an error message will be displayed
1003if the argument was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001004
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001005 >>> parser = argparse.ArgumentParser(prog='game.py')
1006 >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1007 >>> parser.parse_args(['rock'])
1008 Namespace(move='rock')
1009 >>> parser.parse_args(['fire'])
1010 usage: game.py [-h] {rock,paper,scissors}
1011 game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1012 'paper', 'scissors')
Benjamin Petersona39e9662010-03-02 22:05:59 +00001013
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001014Note that inclusion in the *choices* container is checked after any type_
1015conversions have been performed, so the type of the objects in the *choices*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001016container should match the type_ specified::
1017
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001018 >>> parser = argparse.ArgumentParser(prog='doors.py')
1019 >>> parser.add_argument('door', type=int, choices=range(1, 4))
1020 >>> print(parser.parse_args(['3']))
1021 Namespace(door=3)
1022 >>> parser.parse_args(['4'])
1023 usage: doors.py [-h] {1,2,3}
1024 doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001025
Chris Jerdonek92e2fc82013-01-11 19:25:28 -08001026Any object that supports the ``in`` operator can be passed as the *choices*
Georg Brandld2decd92010-03-02 22:17:38 +00001027value, so :class:`dict` objects, :class:`set` objects, custom containers,
1028etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001029
1030
1031required
1032^^^^^^^^
1033
Ezio Melotti01b600c2011-04-21 16:12:17 +03001034In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +03001035indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001036To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +03001037keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001038
1039 >>> parser = argparse.ArgumentParser()
1040 >>> parser.add_argument('--foo', required=True)
1041 >>> parser.parse_args(['--foo', 'BAR'])
1042 Namespace(foo='BAR')
1043 >>> parser.parse_args([])
1044 usage: argparse.py [-h] [--foo FOO]
1045 argparse.py: error: option --foo is required
1046
Ezio Melottic69313a2011-04-22 01:29:13 +03001047As the example shows, if an option is marked as ``required``,
1048:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1049present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001050
Benjamin Peterson90c58022010-03-03 01:55:09 +00001051.. note::
1052
1053 Required options are generally considered bad form because users expect
1054 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001055
1056
1057help
1058^^^^
1059
Benjamin Peterson90c58022010-03-03 01:55:09 +00001060The ``help`` value is a string containing a brief description of the argument.
1061When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001062command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001063argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001064
1065 >>> parser = argparse.ArgumentParser(prog='frobble')
1066 >>> parser.add_argument('--foo', action='store_true',
1067 ... help='foo the bars before frobbling')
1068 >>> parser.add_argument('bar', nargs='+',
1069 ... help='one of the bars to be frobbled')
1070 >>> parser.parse_args('-h'.split())
1071 usage: frobble [-h] [--foo] bar [bar ...]
1072
1073 positional arguments:
1074 bar one of the bars to be frobbled
1075
1076 optional arguments:
1077 -h, --help show this help message and exit
1078 --foo foo the bars before frobbling
1079
1080The ``help`` strings can include various format specifiers to avoid repetition
1081of things like the program name or the argument default_. The available
1082specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001083:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001084
1085 >>> parser = argparse.ArgumentParser(prog='frobble')
1086 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1087 ... help='the bar to %(prog)s (default: %(default)s)')
1088 >>> parser.print_help()
1089 usage: frobble [-h] [bar]
1090
1091 positional arguments:
1092 bar the bar to frobble (default: 42)
1093
1094 optional arguments:
1095 -h, --help show this help message and exit
1096
Sandro Tosi711f5472012-01-03 18:31:51 +01001097:mod:`argparse` supports silencing the help entry for certain options, by
1098setting the ``help`` value to ``argparse.SUPPRESS``::
1099
1100 >>> parser = argparse.ArgumentParser(prog='frobble')
1101 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1102 >>> parser.print_help()
1103 usage: frobble [-h]
1104
1105 optional arguments:
1106 -h, --help show this help message and exit
1107
Benjamin Petersona39e9662010-03-02 22:05:59 +00001108
1109metavar
1110^^^^^^^
1111
Sandro Tosi2534f9a2013-01-11 10:48:34 +01001112When :class:`ArgumentParser` generates help messages, it needs some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001113to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001114value as the "name" of each object. By default, for positional argument
1115actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001116the dest_ value is uppercased. So, a single positional argument with
Eli Benderskybba1dd52011-11-11 16:42:11 +02001117``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujo67719bd2011-08-19 02:00:07 +02001118optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson90c58022010-03-03 01:55:09 +00001119will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001120
1121 >>> parser = argparse.ArgumentParser()
1122 >>> parser.add_argument('--foo')
1123 >>> parser.add_argument('bar')
1124 >>> parser.parse_args('X --foo Y'.split())
1125 Namespace(bar='X', foo='Y')
1126 >>> parser.print_help()
1127 usage: [-h] [--foo FOO] bar
1128
1129 positional arguments:
1130 bar
1131
1132 optional arguments:
1133 -h, --help show this help message and exit
1134 --foo FOO
1135
Benjamin Peterson90c58022010-03-03 01:55:09 +00001136An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001137
1138 >>> parser = argparse.ArgumentParser()
1139 >>> parser.add_argument('--foo', metavar='YYY')
1140 >>> parser.add_argument('bar', metavar='XXX')
1141 >>> parser.parse_args('X --foo Y'.split())
1142 Namespace(bar='X', foo='Y')
1143 >>> parser.print_help()
1144 usage: [-h] [--foo YYY] XXX
1145
1146 positional arguments:
1147 XXX
1148
1149 optional arguments:
1150 -h, --help show this help message and exit
1151 --foo YYY
1152
1153Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001154attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1155by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001156
1157Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001158Providing a tuple to ``metavar`` specifies a different display for each of the
1159arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001160
1161 >>> parser = argparse.ArgumentParser(prog='PROG')
1162 >>> parser.add_argument('-x', nargs=2)
1163 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1164 >>> parser.print_help()
1165 usage: PROG [-h] [-x X X] [--foo bar baz]
1166
1167 optional arguments:
1168 -h, --help show this help message and exit
1169 -x X X
1170 --foo bar baz
1171
1172
1173dest
1174^^^^
1175
Benjamin Peterson90c58022010-03-03 01:55:09 +00001176Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001177object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1178attribute is determined by the ``dest`` keyword argument of
1179:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1180``dest`` is normally supplied as the first argument to
1181:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001182
1183 >>> parser = argparse.ArgumentParser()
1184 >>> parser.add_argument('bar')
1185 >>> parser.parse_args('XXX'.split())
1186 Namespace(bar='XXX')
1187
1188For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001189the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo67719bd2011-08-19 02:00:07 +02001190taking the first long option string and stripping away the initial ``--``
Benjamin Petersona39e9662010-03-02 22:05:59 +00001191string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo67719bd2011-08-19 02:00:07 +02001192the first short option string by stripping the initial ``-`` character. Any
1193internal ``-`` characters will be converted to ``_`` characters to make sure
Georg Brandld2decd92010-03-02 22:17:38 +00001194the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001195behavior::
1196
1197 >>> parser = argparse.ArgumentParser()
1198 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1199 >>> parser.add_argument('-x', '-y')
1200 >>> parser.parse_args('-f 1 -x 2'.split())
1201 Namespace(foo_bar='1', x='2')
1202 >>> parser.parse_args('--foo 1 -y 2'.split())
1203 Namespace(foo_bar='1', x='2')
1204
Benjamin Peterson90c58022010-03-03 01:55:09 +00001205``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001206
1207 >>> parser = argparse.ArgumentParser()
1208 >>> parser.add_argument('--foo', dest='bar')
1209 >>> parser.parse_args('--foo XXX'.split())
1210 Namespace(bar='XXX')
1211
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001212Action classes
1213^^^^^^^^^^^^^^
1214
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001215Action classes implement the Action API, a callable which returns a callable
Benjamin Petersonceb0e1d2014-09-04 11:50:14 -04001216which processes arguments from the command-line. Any object which follows this
1217API may be passed as the ``action`` parameter to :meth:`add_argument`.
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001218
Berker Peksag80154582015-01-06 18:29:04 +02001219.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
1220 type=None, choices=None, required=False, help=None, \
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001221 metavar=None)
1222
Benjamin Petersonceb0e1d2014-09-04 11:50:14 -04001223Action objects are used by an ArgumentParser to represent the information needed
1224to parse a single argument from one or more strings from the command line. The
1225Action class must accept the two positional arguments plus any keyword arguments
1226passed to :meth:`ArgumentParser.add_argument` except for the ``action`` itself.
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001227
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001228Instances of Action (or return value of any callable to the ``action``
1229parameter) should have attributes "dest", "option_strings", "default", "type",
1230"required", "help", etc. defined. The easiest way to ensure these attributes
1231are defined is to call ``Action.__init__``.
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001232
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001233Action instances should be callable, so subclasses must override the
1234``__call__`` method, which should accept four parameters:
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001235
1236* ``parser`` - The ArgumentParser object which contains this action.
1237
1238* ``namespace`` - The :class:`Namespace` object that will be returned by
1239 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1240 object using :func:`setattr`.
1241
1242* ``values`` - The associated command-line arguments, with any type conversions
1243 applied. Type conversions are specified with the type_ keyword argument to
1244 :meth:`~ArgumentParser.add_argument`.
1245
1246* ``option_string`` - The option string that was used to invoke this action.
1247 The ``option_string`` argument is optional, and will be absent if the action
1248 is associated with a positional argument.
1249
Jason R. Coombs69cd3462014-07-20 10:52:46 -04001250The ``__call__`` method may perform arbitrary actions, but will typically set
1251attributes on the ``namespace`` based on ``dest`` and ``values``.
1252
Benjamin Petersona39e9662010-03-02 22:05:59 +00001253
1254The parse_args() method
1255-----------------------
1256
Georg Brandlb8d0e362010-11-26 07:53:50 +00001257.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001258
Benjamin Peterson90c58022010-03-03 01:55:09 +00001259 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001260 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001261
1262 Previous calls to :meth:`add_argument` determine exactly what objects are
1263 created and how they are assigned. See the documentation for
1264 :meth:`add_argument` for details.
1265
Éric Araujo67719bd2011-08-19 02:00:07 +02001266 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001267 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001268
Georg Brandlb8d0e362010-11-26 07:53:50 +00001269
Benjamin Petersona39e9662010-03-02 22:05:59 +00001270Option value syntax
1271^^^^^^^^^^^^^^^^^^^
1272
Ezio Melottic69313a2011-04-22 01:29:13 +03001273The :meth:`~ArgumentParser.parse_args` method supports several ways of
1274specifying the value of an option (if it takes one). In the simplest case, the
1275option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001276
1277 >>> parser = argparse.ArgumentParser(prog='PROG')
1278 >>> parser.add_argument('-x')
1279 >>> parser.add_argument('--foo')
1280 >>> parser.parse_args('-x X'.split())
1281 Namespace(foo=None, x='X')
1282 >>> parser.parse_args('--foo FOO'.split())
1283 Namespace(foo='FOO', x=None)
1284
Benjamin Peterson90c58022010-03-03 01:55:09 +00001285For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001286and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001287separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001288
1289 >>> parser.parse_args('--foo=FOO'.split())
1290 Namespace(foo='FOO', x=None)
1291
Benjamin Peterson90c58022010-03-03 01:55:09 +00001292For short options (options only one character long), the option and its value
1293can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001294
1295 >>> parser.parse_args('-xX'.split())
1296 Namespace(foo=None, x='X')
1297
Benjamin Peterson90c58022010-03-03 01:55:09 +00001298Several short options can be joined together, using only a single ``-`` prefix,
1299as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001300
1301 >>> parser = argparse.ArgumentParser(prog='PROG')
1302 >>> parser.add_argument('-x', action='store_true')
1303 >>> parser.add_argument('-y', action='store_true')
1304 >>> parser.add_argument('-z')
1305 >>> parser.parse_args('-xyzZ'.split())
1306 Namespace(x=True, y=True, z='Z')
1307
1308
1309Invalid arguments
1310^^^^^^^^^^^^^^^^^
1311
Ezio Melottic69313a2011-04-22 01:29:13 +03001312While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1313variety of errors, including ambiguous options, invalid types, invalid options,
1314wrong number of positional arguments, etc. When it encounters such an error,
1315it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001316
1317 >>> parser = argparse.ArgumentParser(prog='PROG')
1318 >>> parser.add_argument('--foo', type=int)
1319 >>> parser.add_argument('bar', nargs='?')
1320
1321 >>> # invalid type
1322 >>> parser.parse_args(['--foo', 'spam'])
1323 usage: PROG [-h] [--foo FOO] [bar]
1324 PROG: error: argument --foo: invalid int value: 'spam'
1325
1326 >>> # invalid option
1327 >>> parser.parse_args(['--bar'])
1328 usage: PROG [-h] [--foo FOO] [bar]
1329 PROG: error: no such option: --bar
1330
1331 >>> # wrong number of arguments
1332 >>> parser.parse_args(['spam', 'badger'])
1333 usage: PROG [-h] [--foo FOO] [bar]
1334 PROG: error: extra arguments found: badger
1335
1336
Éric Araujo67719bd2011-08-19 02:00:07 +02001337Arguments containing ``-``
1338^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001339
Ezio Melottic69313a2011-04-22 01:29:13 +03001340The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1341the user has clearly made a mistake, but some situations are inherently
Éric Araujo67719bd2011-08-19 02:00:07 +02001342ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melottic69313a2011-04-22 01:29:13 +03001343attempt to specify an option or an attempt to provide a positional argument.
1344The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo67719bd2011-08-19 02:00:07 +02001345arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melottic69313a2011-04-22 01:29:13 +03001346there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001347
1348 >>> parser = argparse.ArgumentParser(prog='PROG')
1349 >>> parser.add_argument('-x')
1350 >>> parser.add_argument('foo', nargs='?')
1351
1352 >>> # no negative number options, so -1 is a positional argument
1353 >>> parser.parse_args(['-x', '-1'])
1354 Namespace(foo=None, x='-1')
1355
1356 >>> # no negative number options, so -1 and -5 are positional arguments
1357 >>> parser.parse_args(['-x', '-1', '-5'])
1358 Namespace(foo='-5', x='-1')
1359
1360 >>> parser = argparse.ArgumentParser(prog='PROG')
1361 >>> parser.add_argument('-1', dest='one')
1362 >>> parser.add_argument('foo', nargs='?')
1363
1364 >>> # negative number options present, so -1 is an option
1365 >>> parser.parse_args(['-1', 'X'])
1366 Namespace(foo=None, one='X')
1367
1368 >>> # negative number options present, so -2 is an option
1369 >>> parser.parse_args(['-2'])
1370 usage: PROG [-h] [-1 ONE] [foo]
1371 PROG: error: no such option: -2
1372
1373 >>> # negative number options present, so both -1s are options
1374 >>> parser.parse_args(['-1', '-1'])
1375 usage: PROG [-h] [-1 ONE] [foo]
1376 PROG: error: argument -1: expected one argument
1377
Éric Araujo67719bd2011-08-19 02:00:07 +02001378If you have positional arguments that must begin with ``-`` and don't look
Benjamin Petersona39e9662010-03-02 22:05:59 +00001379like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001380:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1381argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001382
1383 >>> parser.parse_args(['--', '-f'])
1384 Namespace(foo='-f', one=None)
1385
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001386.. _prefix-matching:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001387
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001388Argument abbreviations (prefix matching)
1389^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001390
Ezio Melottic69313a2011-04-22 01:29:13 +03001391The :meth:`~ArgumentParser.parse_args` method allows long options to be
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001392abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
1393a unique option)::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001394
1395 >>> parser = argparse.ArgumentParser(prog='PROG')
1396 >>> parser.add_argument('-bacon')
1397 >>> parser.add_argument('-badger')
1398 >>> parser.parse_args('-bac MMM'.split())
1399 Namespace(bacon='MMM', badger=None)
1400 >>> parser.parse_args('-bad WOOD'.split())
1401 Namespace(bacon=None, badger='WOOD')
1402 >>> parser.parse_args('-ba BA'.split())
1403 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1404 PROG: error: ambiguous option: -ba could match -badger, -bacon
1405
Benjamin Peterson90c58022010-03-03 01:55:09 +00001406An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001407
1408
1409Beyond ``sys.argv``
1410^^^^^^^^^^^^^^^^^^^
1411
Éric Araujo67719bd2011-08-19 02:00:07 +02001412Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Georg Brandld2decd92010-03-02 22:17:38 +00001413of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001414:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1415interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001416
1417 >>> parser = argparse.ArgumentParser()
1418 >>> parser.add_argument(
1419 ... 'integers', metavar='int', type=int, choices=xrange(10),
1420 ... nargs='+', help='an integer in the range 0..9')
1421 >>> parser.add_argument(
1422 ... '--sum', dest='accumulate', action='store_const', const=sum,
1423 ... default=max, help='sum the integers (default: find the max)')
1424 >>> parser.parse_args(['1', '2', '3', '4'])
1425 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1426 >>> parser.parse_args('1 2 3 4 --sum'.split())
1427 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1428
1429
Steven Bethard3f69a052011-03-26 19:59:02 +01001430The Namespace object
1431^^^^^^^^^^^^^^^^^^^^
1432
Éric Araujof0d44bc2011-07-29 17:59:17 +02001433.. class:: Namespace
1434
1435 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1436 an object holding attributes and return it.
1437
1438This class is deliberately simple, just an :class:`object` subclass with a
1439readable string representation. If you prefer to have dict-like view of the
1440attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001441
1442 >>> parser = argparse.ArgumentParser()
1443 >>> parser.add_argument('--foo')
1444 >>> args = parser.parse_args(['--foo', 'BAR'])
1445 >>> vars(args)
1446 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001447
Benjamin Peterson90c58022010-03-03 01:55:09 +00001448It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001449already existing object, rather than a new :class:`Namespace` object. This can
1450be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001451
1452 >>> class C(object):
1453 ... pass
1454 ...
1455 >>> c = C()
1456 >>> parser = argparse.ArgumentParser()
1457 >>> parser.add_argument('--foo')
1458 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1459 >>> c.foo
1460 'BAR'
1461
1462
1463Other utilities
1464---------------
1465
1466Sub-commands
1467^^^^^^^^^^^^
1468
Georg Brandl1f94b262013-10-06 18:51:39 +02001469.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
1470 [parser_class], [action], \
1471 [option_string], [dest], [help], \
1472 [metavar])
Benjamin Petersona39e9662010-03-02 22:05:59 +00001473
Benjamin Peterson90c58022010-03-03 01:55:09 +00001474 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001475 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001476 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001477 this way can be a particularly good idea when a program performs several
1478 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001479 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001480 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
Ezio Melotti82ee3032012-12-28 01:59:24 +02001481 called with no arguments and returns a special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001482 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1483 command name and any :class:`ArgumentParser` constructor arguments, and
1484 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001485
Georg Brandl1f94b262013-10-06 18:51:39 +02001486 Description of parameters:
1487
1488 * title - title for the sub-parser group in help output; by default
1489 "subcommands" if description is provided, otherwise uses title for
1490 positional arguments
1491
1492 * description - description for the sub-parser group in help output, by
1493 default None
1494
1495 * prog - usage information that will be displayed with sub-command help,
1496 by default the name of the program and any positional arguments before the
1497 subparser argument
1498
1499 * parser_class - class which will be used to create sub-parser instances, by
1500 default the class of the current parser (e.g. ArgumentParser)
1501
Berker Peksag1b6e5382015-01-20 06:55:51 +02001502 * action_ - the basic type of action to be taken when this argument is
1503 encountered at the command line
1504
1505 * dest_ - name of the attribute under which sub-command name will be
Georg Brandl1f94b262013-10-06 18:51:39 +02001506 stored; by default None and no value is stored
1507
Berker Peksag1b6e5382015-01-20 06:55:51 +02001508 * help_ - help for sub-parser group in help output, by default None
Georg Brandl1f94b262013-10-06 18:51:39 +02001509
Berker Peksag1b6e5382015-01-20 06:55:51 +02001510 * metavar_ - string presenting available sub-commands in help; by default it
Georg Brandl1f94b262013-10-06 18:51:39 +02001511 is None and presents sub-commands in form {cmd1, cmd2, ..}
1512
Benjamin Petersona39e9662010-03-02 22:05:59 +00001513 Some example usage::
1514
1515 >>> # create the top-level parser
1516 >>> parser = argparse.ArgumentParser(prog='PROG')
1517 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1518 >>> subparsers = parser.add_subparsers(help='sub-command help')
1519 >>>
1520 >>> # create the parser for the "a" command
1521 >>> parser_a = subparsers.add_parser('a', help='a help')
1522 >>> parser_a.add_argument('bar', type=int, help='bar help')
1523 >>>
1524 >>> # create the parser for the "b" command
1525 >>> parser_b = subparsers.add_parser('b', help='b help')
1526 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1527 >>>
Éric Araujo67719bd2011-08-19 02:00:07 +02001528 >>> # parse some argument lists
Benjamin Petersona39e9662010-03-02 22:05:59 +00001529 >>> parser.parse_args(['a', '12'])
1530 Namespace(bar=12, foo=False)
1531 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1532 Namespace(baz='Z', foo=True)
1533
1534 Note that the object returned by :meth:`parse_args` will only contain
1535 attributes for the main parser and the subparser that was selected by the
1536 command line (and not any other subparsers). So in the example above, when
Éric Araujo67719bd2011-08-19 02:00:07 +02001537 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1538 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001539 ``baz`` attributes are present.
1540
1541 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001542 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001543 include parent parser or sibling parser messages. (A help message for each
1544 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001545 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001546
1547 ::
1548
1549 >>> parser.parse_args(['--help'])
1550 usage: PROG [-h] [--foo] {a,b} ...
1551
1552 positional arguments:
1553 {a,b} sub-command help
Ezio Melottidc157fc2013-01-12 10:39:45 +02001554 a a help
1555 b b help
Benjamin Petersona39e9662010-03-02 22:05:59 +00001556
1557 optional arguments:
1558 -h, --help show this help message and exit
1559 --foo foo help
1560
1561 >>> parser.parse_args(['a', '--help'])
1562 usage: PROG a [-h] bar
1563
1564 positional arguments:
1565 bar bar help
1566
1567 optional arguments:
1568 -h, --help show this help message and exit
1569
1570 >>> parser.parse_args(['b', '--help'])
1571 usage: PROG b [-h] [--baz {X,Y,Z}]
1572
1573 optional arguments:
1574 -h, --help show this help message and exit
1575 --baz {X,Y,Z} baz help
1576
Georg Brandld2decd92010-03-02 22:17:38 +00001577 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1578 keyword arguments. When either is present, the subparser's commands will
1579 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001580
1581 >>> parser = argparse.ArgumentParser()
1582 >>> subparsers = parser.add_subparsers(title='subcommands',
1583 ... description='valid subcommands',
1584 ... help='additional help')
1585 >>> subparsers.add_parser('foo')
1586 >>> subparsers.add_parser('bar')
1587 >>> parser.parse_args(['-h'])
1588 usage: [-h] {foo,bar} ...
1589
1590 optional arguments:
1591 -h, --help show this help message and exit
1592
1593 subcommands:
1594 valid subcommands
1595
1596 {foo,bar} additional help
1597
1598
Georg Brandld2decd92010-03-02 22:17:38 +00001599 One particularly effective way of handling sub-commands is to combine the use
1600 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1601 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001602 example::
1603
1604 >>> # sub-command functions
1605 >>> def foo(args):
1606 ... print args.x * args.y
1607 ...
1608 >>> def bar(args):
1609 ... print '((%s))' % args.z
1610 ...
1611 >>> # create the top-level parser
1612 >>> parser = argparse.ArgumentParser()
1613 >>> subparsers = parser.add_subparsers()
1614 >>>
1615 >>> # create the parser for the "foo" command
1616 >>> parser_foo = subparsers.add_parser('foo')
1617 >>> parser_foo.add_argument('-x', type=int, default=1)
1618 >>> parser_foo.add_argument('y', type=float)
1619 >>> parser_foo.set_defaults(func=foo)
1620 >>>
1621 >>> # create the parser for the "bar" command
1622 >>> parser_bar = subparsers.add_parser('bar')
1623 >>> parser_bar.add_argument('z')
1624 >>> parser_bar.set_defaults(func=bar)
1625 >>>
1626 >>> # parse the args and call whatever function was selected
1627 >>> args = parser.parse_args('foo 1 -x 2'.split())
1628 >>> args.func(args)
1629 2.0
1630 >>>
1631 >>> # parse the args and call whatever function was selected
1632 >>> args = parser.parse_args('bar XYZYX'.split())
1633 >>> args.func(args)
1634 ((XYZYX))
1635
Éric Araujobb42f5e2012-02-20 02:08:01 +01001636 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson90c58022010-03-03 01:55:09 +00001637 appropriate function after argument parsing is complete. Associating
1638 functions with actions like this is typically the easiest way to handle the
1639 different actions for each of your subparsers. However, if it is necessary
1640 to check the name of the subparser that was invoked, the ``dest`` keyword
1641 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001642
1643 >>> parser = argparse.ArgumentParser()
1644 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1645 >>> subparser1 = subparsers.add_parser('1')
1646 >>> subparser1.add_argument('-x')
1647 >>> subparser2 = subparsers.add_parser('2')
1648 >>> subparser2.add_argument('y')
1649 >>> parser.parse_args(['2', 'frobble'])
1650 Namespace(subparser_name='2', y='frobble')
1651
1652
1653FileType objects
1654^^^^^^^^^^^^^^^^
1655
1656.. class:: FileType(mode='r', bufsize=None)
1657
1658 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001659 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujo67719bd2011-08-19 02:00:07 +02001660 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujobb42f5e2012-02-20 02:08:01 +01001661 with the requested modes and buffer sizes::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001662
Éric Araujobb42f5e2012-02-20 02:08:01 +01001663 >>> parser = argparse.ArgumentParser()
1664 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1665 >>> parser.parse_args(['--output', 'out'])
1666 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001667
1668 FileType objects understand the pseudo-argument ``'-'`` and automatically
1669 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujobb42f5e2012-02-20 02:08:01 +01001670 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001671
Éric Araujobb42f5e2012-02-20 02:08:01 +01001672 >>> parser = argparse.ArgumentParser()
1673 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1674 >>> parser.parse_args(['-'])
1675 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001676
1677
1678Argument groups
1679^^^^^^^^^^^^^^^
1680
Georg Brandlb8d0e362010-11-26 07:53:50 +00001681.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001682
Benjamin Peterson90c58022010-03-03 01:55:09 +00001683 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001684 "positional arguments" and "optional arguments" when displaying help
1685 messages. When there is a better conceptual grouping of arguments than this
1686 default one, appropriate groups can be created using the
1687 :meth:`add_argument_group` method::
1688
1689 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1690 >>> group = parser.add_argument_group('group')
1691 >>> group.add_argument('--foo', help='foo help')
1692 >>> group.add_argument('bar', help='bar help')
1693 >>> parser.print_help()
1694 usage: PROG [--foo FOO] bar
1695
1696 group:
1697 bar bar help
1698 --foo FOO foo help
1699
1700 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001701 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1702 :class:`ArgumentParser`. When an argument is added to the group, the parser
1703 treats it just like a normal argument, but displays the argument in a
1704 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001705 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001706 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001707
1708 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1709 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1710 >>> group1.add_argument('foo', help='foo help')
1711 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1712 >>> group2.add_argument('--bar', help='bar help')
1713 >>> parser.print_help()
1714 usage: PROG [--bar BAR] foo
1715
1716 group1:
1717 group1 description
1718
1719 foo foo help
1720
1721 group2:
1722 group2 description
1723
1724 --bar BAR bar help
1725
Sandro Tosi48a88952012-03-26 19:35:52 +02001726 Note that any arguments not in your user-defined groups will end up back
1727 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001728
1729
1730Mutual exclusion
1731^^^^^^^^^^^^^^^^
1732
Georg Brandle3005462013-10-06 13:09:59 +02001733.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001734
Ezio Melotti01b600c2011-04-21 16:12:17 +03001735 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1736 one of the arguments in the mutually exclusive group was present on the
1737 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001738
1739 >>> parser = argparse.ArgumentParser(prog='PROG')
1740 >>> group = parser.add_mutually_exclusive_group()
1741 >>> group.add_argument('--foo', action='store_true')
1742 >>> group.add_argument('--bar', action='store_false')
1743 >>> parser.parse_args(['--foo'])
1744 Namespace(bar=True, foo=True)
1745 >>> parser.parse_args(['--bar'])
1746 Namespace(bar=False, foo=False)
1747 >>> parser.parse_args(['--foo', '--bar'])
1748 usage: PROG [-h] [--foo | --bar]
1749 PROG: error: argument --bar: not allowed with argument --foo
1750
Georg Brandlb8d0e362010-11-26 07:53:50 +00001751 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001752 argument, to indicate that at least one of the mutually exclusive arguments
1753 is required::
1754
1755 >>> parser = argparse.ArgumentParser(prog='PROG')
1756 >>> group = parser.add_mutually_exclusive_group(required=True)
1757 >>> group.add_argument('--foo', action='store_true')
1758 >>> group.add_argument('--bar', action='store_false')
1759 >>> parser.parse_args([])
1760 usage: PROG [-h] (--foo | --bar)
1761 PROG: error: one of the arguments --foo --bar is required
1762
1763 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001764 *title* and *description* arguments of
1765 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001766
1767
1768Parser defaults
1769^^^^^^^^^^^^^^^
1770
Benjamin Peterson90c58022010-03-03 01:55:09 +00001771.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001772
Georg Brandld2decd92010-03-02 22:17:38 +00001773 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujo67719bd2011-08-19 02:00:07 +02001774 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001775 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001776 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001777 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001778
1779 >>> parser = argparse.ArgumentParser()
1780 >>> parser.add_argument('foo', type=int)
1781 >>> parser.set_defaults(bar=42, baz='badger')
1782 >>> parser.parse_args(['736'])
1783 Namespace(bar=42, baz='badger', foo=736)
1784
Benjamin Peterson90c58022010-03-03 01:55:09 +00001785 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001786
1787 >>> parser = argparse.ArgumentParser()
1788 >>> parser.add_argument('--foo', default='bar')
1789 >>> parser.set_defaults(foo='spam')
1790 >>> parser.parse_args([])
1791 Namespace(foo='spam')
1792
Benjamin Peterson90c58022010-03-03 01:55:09 +00001793 Parser-level defaults can be particularly useful when working with multiple
1794 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1795 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001796
Benjamin Peterson90c58022010-03-03 01:55:09 +00001797.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001798
1799 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001800 :meth:`~ArgumentParser.add_argument` or by
1801 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001802
1803 >>> parser = argparse.ArgumentParser()
1804 >>> parser.add_argument('--foo', default='badger')
1805 >>> parser.get_default('foo')
1806 'badger'
1807
1808
1809Printing help
1810^^^^^^^^^^^^^
1811
Ezio Melottic69313a2011-04-22 01:29:13 +03001812In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1813care of formatting and printing any usage or error messages. However, several
1814formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001815
Georg Brandlb8d0e362010-11-26 07:53:50 +00001816.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001817
1818 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001819 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001820 assumed.
1821
Georg Brandlb8d0e362010-11-26 07:53:50 +00001822.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001823
1824 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001825 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001826 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001827
1828There are also variants of these methods that simply return a string instead of
1829printing it:
1830
Georg Brandlb8d0e362010-11-26 07:53:50 +00001831.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001832
1833 Return a string containing a brief description of how the
1834 :class:`ArgumentParser` should be invoked on the command line.
1835
Georg Brandlb8d0e362010-11-26 07:53:50 +00001836.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001837
1838 Return a string containing a help message, including the program usage and
1839 information about the arguments registered with the :class:`ArgumentParser`.
1840
1841
Benjamin Petersona39e9662010-03-02 22:05:59 +00001842Partial parsing
1843^^^^^^^^^^^^^^^
1844
Georg Brandlb8d0e362010-11-26 07:53:50 +00001845.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001846
Ezio Melotti12125822011-04-16 23:04:51 +03001847Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001848the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001849:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001850:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1851extra arguments are present. Instead, it returns a two item tuple containing
1852the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001853
1854::
1855
1856 >>> parser = argparse.ArgumentParser()
1857 >>> parser.add_argument('--foo', action='store_true')
1858 >>> parser.add_argument('bar')
1859 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1860 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1861
Eli Bendersky7b2ac602013-12-02 05:53:35 -08001862.. warning::
1863 :ref:`Prefix matching <prefix-matching>` rules apply to
1864 :meth:`parse_known_args`. The parser may consume an option even if it's just
1865 a prefix of one of its known options, instead of leaving it in the remaining
1866 arguments list.
1867
Benjamin Petersona39e9662010-03-02 22:05:59 +00001868
1869Customizing file parsing
1870^^^^^^^^^^^^^^^^^^^^^^^^
1871
Benjamin Peterson90c58022010-03-03 01:55:09 +00001872.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001873
Georg Brandlb8d0e362010-11-26 07:53:50 +00001874 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001875 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001876 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1877 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001878
Georg Brandlb8d0e362010-11-26 07:53:50 +00001879 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001880 the argument file. It returns a list of arguments parsed from this string.
1881 The method is called once per line read from the argument file, in order.
1882
Georg Brandld2decd92010-03-02 22:17:38 +00001883 A useful override of this method is one that treats each space-separated word
1884 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001885
1886 def convert_arg_line_to_args(self, arg_line):
1887 for arg in arg_line.split():
1888 if not arg.strip():
1889 continue
1890 yield arg
1891
1892
Georg Brandlb8d0e362010-11-26 07:53:50 +00001893Exiting methods
1894^^^^^^^^^^^^^^^
1895
1896.. method:: ArgumentParser.exit(status=0, message=None)
1897
1898 This method terminates the program, exiting with the specified *status*
1899 and, if given, it prints a *message* before that.
1900
1901.. method:: ArgumentParser.error(message)
1902
1903 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001904 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001905
1906
Georg Brandl58df6792010-07-03 10:25:47 +00001907.. _argparse-from-optparse:
1908
Benjamin Petersona39e9662010-03-02 22:05:59 +00001909Upgrading optparse code
1910-----------------------
1911
Ezio Melottic69313a2011-04-22 01:29:13 +03001912Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001913with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1914transparently, particularly with the changes required to support the new
1915``nargs=`` specifiers and better usage messages. When most everything in
1916:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1917longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001918
Berker Peksag12f05322014-09-26 15:39:05 +03001919The :mod:`argparse` module improves on the standard library :mod:`optparse`
1920module in a number of ways including:
1921
1922* Handling positional arguments.
1923* Supporting sub-commands.
1924* Allowing alternative option prefixes like ``+`` and ``/``.
1925* Handling zero-or-more and one-or-more style arguments.
1926* Producing more informative usage messages.
1927* Providing a much simpler interface for custom ``type`` and ``action``.
1928
Ezio Melotti01b600c2011-04-21 16:12:17 +03001929A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001930
Ezio Melottic69313a2011-04-22 01:29:13 +03001931* Replace all :meth:`optparse.OptionParser.add_option` calls with
1932 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001933
R David Murray5080cad2012-03-30 18:09:07 -04001934* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001935 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5080cad2012-03-30 18:09:07 -04001936 calls for the positional arguments. Keep in mind that what was previously
1937 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001938
1939* Replace callback actions and the ``callback_*`` keyword arguments with
1940 ``type`` or ``action`` arguments.
1941
1942* Replace string names for ``type`` keyword arguments with the corresponding
1943 type objects (e.g. int, float, complex, etc).
1944
Benjamin Peterson90c58022010-03-03 01:55:09 +00001945* Replace :class:`optparse.Values` with :class:`Namespace` and
1946 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1947 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001948
Georg Brandld2decd92010-03-02 22:17:38 +00001949* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001950 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001951 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001952
1953* Replace the OptionParser constructor ``version`` argument with a call to
1954 ``parser.add_argument('--version', action='version', version='<the version>')``