blob: 8bb740e83ee0c6683b646d5d6e02e902c1544d4a [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
49 $ prog.py -h
50 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
64 $ prog.py 1 2 3 4
65 4
66
67 $ prog.py 1 2 3 4 --sum
68 10
69
70If invalid arguments are passed in, it will issue an error::
71
72 $ prog.py a b c
73 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
Georg Brandld2decd92010-03-02 22:17:38 +0000140 Create a new :class:`ArgumentParser` object. Each parameter has its own more
Benjamin Petersona39e9662010-03-02 22:05:59 +0000141 detailed description below, but in short they are:
142
143 * description_ - Text to display before the argument help.
144
145 * epilog_ - Text to display after the argument help.
146
Benjamin Peterson90c58022010-03-03 01:55:09 +0000147 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000148
149 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000150 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000151
Benjamin Peterson90c58022010-03-03 01:55:09 +0000152 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Petersona39e9662010-03-02 22:05:59 +0000153 also be included.
154
155 * prefix_chars_ - The set of characters that prefix optional arguments.
156 (default: '-')
157
158 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson90c58022010-03-03 01:55:09 +0000159 which additional arguments should be read. (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000160
161 * formatter_class_ - A class for customizing the help output.
162
163 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
164 conflicting optionals.
165
Benjamin Peterson90c58022010-03-03 01:55:09 +0000166 * prog_ - The name of the program (default:
Éric Araujo7ce05e02011-09-01 19:54:05 +0200167 ``sys.argv[0]``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000168
Benjamin Peterson90c58022010-03-03 01:55:09 +0000169 * usage_ - The string describing the program usage (default: generated)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000170
Benjamin Peterson90c58022010-03-03 01:55:09 +0000171The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000172
173
174description
175^^^^^^^^^^^
176
Benjamin Peterson90c58022010-03-03 01:55:09 +0000177Most calls to the :class:`ArgumentParser` constructor will use the
178``description=`` keyword argument. This argument gives a brief description of
179what the program does and how it works. In help messages, the description is
180displayed between the command-line usage string and the help messages for the
181various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000182
183 >>> parser = argparse.ArgumentParser(description='A foo that bars')
184 >>> parser.print_help()
185 usage: argparse.py [-h]
186
187 A foo that bars
188
189 optional arguments:
190 -h, --help show this help message and exit
191
192By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000193given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000194
195
196epilog
197^^^^^^
198
199Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000200description of the arguments. Such text can be specified using the ``epilog=``
201argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000202
203 >>> parser = argparse.ArgumentParser(
204 ... description='A foo that bars',
205 ... epilog="And that's how you'd foo a bar")
206 >>> parser.print_help()
207 usage: argparse.py [-h]
208
209 A foo that bars
210
211 optional arguments:
212 -h, --help show this help message and exit
213
214 And that's how you'd foo a bar
215
216As with the description_ argument, the ``epilog=`` text is by default
217line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000218argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000219
220
221add_help
222^^^^^^^^
223
R. David Murray1cbf78e2010-08-03 18:14:01 +0000224By default, ArgumentParser objects add an option which simply displays
225the parser's help message. For example, consider a file named
Benjamin Petersona39e9662010-03-02 22:05:59 +0000226``myprogram.py`` containing the following code::
227
228 import argparse
229 parser = argparse.ArgumentParser()
230 parser.add_argument('--foo', help='foo help')
231 args = parser.parse_args()
232
Ezio Melotti12125822011-04-16 23:04:51 +0300233If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Petersona39e9662010-03-02 22:05:59 +0000234help will be printed::
235
236 $ python myprogram.py --help
237 usage: myprogram.py [-h] [--foo FOO]
238
239 optional arguments:
240 -h, --help show this help message and exit
241 --foo FOO foo help
242
243Occasionally, it may be useful to disable the addition of this help option.
244This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson90c58022010-03-03 01:55:09 +0000245:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000246
247 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
248 >>> parser.add_argument('--foo', help='foo help')
249 >>> parser.print_help()
250 usage: PROG [--foo FOO]
251
252 optional arguments:
253 --foo FOO foo help
254
R. David Murray1cbf78e2010-08-03 18:14:01 +0000255The help option is typically ``-h/--help``. The exception to this is
Éric Araujo67719bd2011-08-19 02:00:07 +0200256if the ``prefix_chars=`` is specified and does not include ``-``, in
R. David Murray1cbf78e2010-08-03 18:14:01 +0000257which case ``-h`` and ``--help`` are not valid options. In
258this case, the first character in ``prefix_chars`` is used to prefix
259the help options::
260
261 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
262 >>> parser.print_help()
263 usage: PROG [+h]
264
265 optional arguments:
266 +h, ++help show this help message and exit
267
268
Benjamin Petersona39e9662010-03-02 22:05:59 +0000269prefix_chars
270^^^^^^^^^^^^
271
Éric Araujo67719bd2011-08-19 02:00:07 +0200272Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
R. David Murray1cbf78e2010-08-03 18:14:01 +0000273Parsers that need to support different or additional prefix
274characters, e.g. for options
Benjamin Petersona39e9662010-03-02 22:05:59 +0000275like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
276to the ArgumentParser constructor::
277
278 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
279 >>> parser.add_argument('+f')
280 >>> parser.add_argument('++bar')
281 >>> parser.parse_args('+f X ++bar Y'.split())
282 Namespace(bar='Y', f='X')
283
284The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
Éric Araujo67719bd2011-08-19 02:00:07 +0200285characters that does not include ``-`` will cause ``-f/--foo`` options to be
Benjamin Petersona39e9662010-03-02 22:05:59 +0000286disallowed.
287
288
289fromfile_prefix_chars
290^^^^^^^^^^^^^^^^^^^^^
291
Benjamin Peterson90c58022010-03-03 01:55:09 +0000292Sometimes, for example when dealing with a particularly long argument lists, it
293may make sense to keep the list of arguments in a file rather than typing it out
294at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
295:class:`ArgumentParser` constructor, then arguments that start with any of the
296specified characters will be treated as files, and will be replaced by the
297arguments they contain. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000298
Benjamin Peterson90c58022010-03-03 01:55:09 +0000299 >>> with open('args.txt', 'w') as fp:
300 ... fp.write('-f\nbar')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000301 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
302 >>> parser.add_argument('-f')
303 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
304 Namespace(f='bar')
305
306Arguments read from a file must by default be one per line (but see also
Ezio Melottic69313a2011-04-22 01:29:13 +0300307:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
308were in the same place as the original file referencing argument on the command
309line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
310is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000311
312The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
313arguments will never be treated as file references.
314
Georg Brandlb8d0e362010-11-26 07:53:50 +0000315
Benjamin Petersona39e9662010-03-02 22:05:59 +0000316argument_default
317^^^^^^^^^^^^^^^^
318
319Generally, argument defaults are specified either by passing a default to
Ezio Melottic69313a2011-04-22 01:29:13 +0300320:meth:`~ArgumentParser.add_argument` or by calling the
321:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
322pairs. Sometimes however, it may be useful to specify a single parser-wide
323default for arguments. This can be accomplished by passing the
324``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
325to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson90c58022010-03-03 01:55:09 +0000326calls, we supply ``argument_default=SUPPRESS``::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000327
328 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
329 >>> parser.add_argument('--foo')
330 >>> parser.add_argument('bar', nargs='?')
331 >>> parser.parse_args(['--foo', '1', 'BAR'])
332 Namespace(bar='BAR', foo='1')
333 >>> parser.parse_args([])
334 Namespace()
335
336
337parents
338^^^^^^^
339
340Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000341repeating the definitions of these arguments, a single parser with all the
342shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
343can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
344objects, collects all the positional and optional actions from them, and adds
345these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000346
347 >>> parent_parser = argparse.ArgumentParser(add_help=False)
348 >>> parent_parser.add_argument('--parent', type=int)
349
350 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
351 >>> foo_parser.add_argument('foo')
352 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
353 Namespace(foo='XXX', parent=2)
354
355 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
356 >>> bar_parser.add_argument('--bar')
357 >>> bar_parser.parse_args(['--bar', 'YYY'])
358 Namespace(bar='YYY', parent=None)
359
Georg Brandld2decd92010-03-02 22:17:38 +0000360Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000361:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
362and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000363
Steven Bethard5e0062d2011-03-26 21:50:38 +0100364.. note::
365 You must fully initialize the parsers before passing them via ``parents=``.
366 If you change the parent parsers after the child parser, those changes will
367 not be reflected in the child.
368
Benjamin Petersona39e9662010-03-02 22:05:59 +0000369
370formatter_class
371^^^^^^^^^^^^^^^
372
Benjamin Peterson90c58022010-03-03 01:55:09 +0000373:class:`ArgumentParser` objects allow the help formatting to be customized by
374specifying an alternate formatting class. Currently, there are three such
Ezio Melottic69313a2011-04-22 01:29:13 +0300375classes:
376
377.. class:: RawDescriptionHelpFormatter
378 RawTextHelpFormatter
379 ArgumentDefaultsHelpFormatter
380
381The first two allow more control over how textual descriptions are displayed,
382while the last automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000383
Benjamin Peterson90c58022010-03-03 01:55:09 +0000384By default, :class:`ArgumentParser` objects line-wrap the description_ and
385epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000386
387 >>> parser = argparse.ArgumentParser(
388 ... prog='PROG',
389 ... description='''this description
390 ... was indented weird
391 ... but that is okay''',
392 ... epilog='''
393 ... likewise for this epilog whose whitespace will
394 ... be cleaned up and whose words will be wrapped
395 ... across a couple lines''')
396 >>> parser.print_help()
397 usage: PROG [-h]
398
399 this description was indented weird but that is okay
400
401 optional arguments:
402 -h, --help show this help message and exit
403
404 likewise for this epilog whose whitespace will be cleaned up and whose words
405 will be wrapped across a couple lines
406
Éric Araujo67719bd2011-08-19 02:00:07 +0200407Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000408indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000409should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000410
411 >>> parser = argparse.ArgumentParser(
412 ... prog='PROG',
413 ... formatter_class=argparse.RawDescriptionHelpFormatter,
414 ... description=textwrap.dedent('''\
415 ... Please do not mess up this text!
416 ... --------------------------------
417 ... I have indented it
418 ... exactly the way
419 ... I want it
420 ... '''))
421 >>> parser.print_help()
422 usage: PROG [-h]
423
424 Please do not mess up this text!
425 --------------------------------
426 I have indented it
427 exactly the way
428 I want it
429
430 optional arguments:
431 -h, --help show this help message and exit
432
Éric Araujo67719bd2011-08-19 02:00:07 +0200433:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson90c58022010-03-03 01:55:09 +0000434including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000435
Benjamin Peterson90c58022010-03-03 01:55:09 +0000436The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000437will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000438
439 >>> parser = argparse.ArgumentParser(
440 ... prog='PROG',
441 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
442 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
443 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
444 >>> parser.print_help()
445 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
446
447 positional arguments:
448 bar BAR! (default: [1, 2, 3])
449
450 optional arguments:
451 -h, --help show this help message and exit
452 --foo FOO FOO! (default: 42)
453
454
455conflict_handler
456^^^^^^^^^^^^^^^^
457
Benjamin Peterson90c58022010-03-03 01:55:09 +0000458:class:`ArgumentParser` objects do not allow two actions with the same option
459string. By default, :class:`ArgumentParser` objects raises an exception if an
460attempt is made to create an argument with an option string that is already in
461use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000462
463 >>> parser = argparse.ArgumentParser(prog='PROG')
464 >>> parser.add_argument('-f', '--foo', help='old foo help')
465 >>> parser.add_argument('--foo', help='new foo help')
466 Traceback (most recent call last):
467 ..
468 ArgumentError: argument --foo: conflicting option string(s): --foo
469
470Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000471older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000472``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000473:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000474
475 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
476 >>> parser.add_argument('-f', '--foo', help='old foo help')
477 >>> parser.add_argument('--foo', help='new foo help')
478 >>> parser.print_help()
479 usage: PROG [-h] [-f FOO] [--foo FOO]
480
481 optional arguments:
482 -h, --help show this help message and exit
483 -f FOO old foo help
484 --foo FOO new foo help
485
Benjamin Peterson90c58022010-03-03 01:55:09 +0000486Note that :class:`ArgumentParser` objects only remove an action if all of its
487option strings are overridden. So, in the example above, the old ``-f/--foo``
488action is retained as the ``-f`` action, because only the ``--foo`` option
489string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000490
491
492prog
493^^^^
494
Benjamin Peterson90c58022010-03-03 01:55:09 +0000495By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
496how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000497always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000498invoked on the command line. For example, consider a file named
499``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000500
501 import argparse
502 parser = argparse.ArgumentParser()
503 parser.add_argument('--foo', help='foo help')
504 args = parser.parse_args()
505
506The help for this program will display ``myprogram.py`` as the program name
507(regardless of where the program was invoked from)::
508
509 $ python myprogram.py --help
510 usage: myprogram.py [-h] [--foo FOO]
511
512 optional arguments:
513 -h, --help show this help message and exit
514 --foo FOO foo help
515 $ cd ..
516 $ python subdir\myprogram.py --help
517 usage: myprogram.py [-h] [--foo FOO]
518
519 optional arguments:
520 -h, --help show this help message and exit
521 --foo FOO foo help
522
523To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000524``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000525
526 >>> parser = argparse.ArgumentParser(prog='myprogram')
527 >>> parser.print_help()
528 usage: myprogram [-h]
529
530 optional arguments:
531 -h, --help show this help message and exit
532
533Note that the program name, whether determined from ``sys.argv[0]`` or from the
534``prog=`` argument, is available to help messages using the ``%(prog)s`` format
535specifier.
536
537::
538
539 >>> parser = argparse.ArgumentParser(prog='myprogram')
540 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
541 >>> parser.print_help()
542 usage: myprogram [-h] [--foo FOO]
543
544 optional arguments:
545 -h, --help show this help message and exit
546 --foo FOO foo of the myprogram program
547
548
549usage
550^^^^^
551
Benjamin Peterson90c58022010-03-03 01:55:09 +0000552By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000553arguments it contains::
554
555 >>> parser = argparse.ArgumentParser(prog='PROG')
556 >>> parser.add_argument('--foo', nargs='?', help='foo help')
557 >>> parser.add_argument('bar', nargs='+', help='bar help')
558 >>> parser.print_help()
559 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
560
561 positional arguments:
562 bar bar help
563
564 optional arguments:
565 -h, --help show this help message and exit
566 --foo [FOO] foo help
567
Benjamin Peterson90c58022010-03-03 01:55:09 +0000568The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000569
570 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
571 >>> parser.add_argument('--foo', nargs='?', help='foo help')
572 >>> parser.add_argument('bar', nargs='+', help='bar help')
573 >>> parser.print_help()
574 usage: PROG [options]
575
576 positional arguments:
577 bar bar help
578
579 optional arguments:
580 -h, --help show this help message and exit
581 --foo [FOO] foo help
582
Benjamin Peterson90c58022010-03-03 01:55:09 +0000583The ``%(prog)s`` format specifier is available to fill in the program name in
584your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000585
586
587The add_argument() method
588-------------------------
589
Éric Araujobb42f5e2012-02-20 02:08:01 +0100590.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
591 [const], [default], [type], [choices], [required], \
592 [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000593
Ezio Melotti12125822011-04-16 23:04:51 +0300594 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000595 has its own more detailed description below, but in short they are:
596
597 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300598 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000599
600 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300601 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000602
603 * nargs_ - The number of command-line arguments that should be consumed.
604
605 * const_ - A constant value required by some action_ and nargs_ selections.
606
607 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300608 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000609
Ezio Melotti12125822011-04-16 23:04:51 +0300610 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000611
612 * choices_ - A container of the allowable values for the argument.
613
614 * required_ - Whether or not the command-line option may be omitted
615 (optionals only).
616
617 * help_ - A brief description of what the argument does.
618
619 * metavar_ - A name for the argument in usage messages.
620
621 * dest_ - The name of the attribute to be added to the object returned by
622 :meth:`parse_args`.
623
Benjamin Peterson90c58022010-03-03 01:55:09 +0000624The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000625
Georg Brandlb8d0e362010-11-26 07:53:50 +0000626
Benjamin Petersona39e9662010-03-02 22:05:59 +0000627name or flags
628^^^^^^^^^^^^^
629
Ezio Melottic69313a2011-04-22 01:29:13 +0300630The :meth:`~ArgumentParser.add_argument` method must know whether an optional
631argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
632filenames, is expected. The first arguments passed to
633:meth:`~ArgumentParser.add_argument` must therefore be either a series of
634flags, or a simple argument name. For example, an optional argument could
635be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000636
637 >>> parser.add_argument('-f', '--foo')
638
639while a positional argument could be created like::
640
641 >>> parser.add_argument('bar')
642
Ezio Melottic69313a2011-04-22 01:29:13 +0300643When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
644identified by the ``-`` prefix, and the remaining arguments will be assumed to
645be positional::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000646
647 >>> parser = argparse.ArgumentParser(prog='PROG')
648 >>> parser.add_argument('-f', '--foo')
649 >>> parser.add_argument('bar')
650 >>> parser.parse_args(['BAR'])
651 Namespace(bar='BAR', foo=None)
652 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
653 Namespace(bar='BAR', foo='FOO')
654 >>> parser.parse_args(['--foo', 'FOO'])
655 usage: PROG [-h] [-f FOO] bar
656 PROG: error: too few arguments
657
Georg Brandlb8d0e362010-11-26 07:53:50 +0000658
Benjamin Petersona39e9662010-03-02 22:05:59 +0000659action
660^^^^^^
661
Éric Araujo67719bd2011-08-19 02:00:07 +0200662:class:`ArgumentParser` objects associate command-line arguments with actions. These
663actions can do just about anything with the command-line arguments associated with
Benjamin Petersona39e9662010-03-02 22:05:59 +0000664them, though most actions simply add an attribute to the object returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300665:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Éric Araujo67719bd2011-08-19 02:00:07 +0200666how the command-line arguments should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000667
Georg Brandld2decd92010-03-02 22:17:38 +0000668* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300669 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000670
671 >>> parser = argparse.ArgumentParser()
672 >>> parser.add_argument('--foo')
673 >>> parser.parse_args('--foo 1'.split())
674 Namespace(foo='1')
675
676* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti310619c2011-04-21 23:06:48 +0300677 argument. (Note that the const_ keyword argument defaults to the rather
678 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
679 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000680
681 >>> parser = argparse.ArgumentParser()
682 >>> parser.add_argument('--foo', action='store_const', const=42)
683 >>> parser.parse_args('--foo'.split())
684 Namespace(foo=42)
685
Raymond Hettinger421467f2011-11-20 11:05:23 -0800686* ``'store_true'`` and ``'store_false'`` - These are special cases of
687 ``'store_const'`` using for storing the values ``True`` and ``False``
688 respectively. In addition, they create default values of *False* and *True*
689 respectively. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000690
691 >>> parser = argparse.ArgumentParser()
692 >>> parser.add_argument('--foo', action='store_true')
693 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettinger421467f2011-11-20 11:05:23 -0800694 >>> parser.add_argument('--baz', action='store_false')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000695 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettinger421467f2011-11-20 11:05:23 -0800696 Namespace(bar=False, baz=True, foo=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000697
698* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000699 list. This is useful to allow an option to be specified multiple times.
700 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000701
702 >>> parser = argparse.ArgumentParser()
703 >>> parser.add_argument('--foo', action='append')
704 >>> parser.parse_args('--foo 1 --foo 2'.split())
705 Namespace(foo=['1', '2'])
706
707* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000708 the const_ keyword argument to the list. (Note that the const_ keyword
709 argument defaults to ``None``.) The ``'append_const'`` action is typically
710 useful when multiple arguments need to store constants to the same list. For
711 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000712
713 >>> parser = argparse.ArgumentParser()
714 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
715 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
716 >>> parser.parse_args('--str --int'.split())
717 Namespace(types=[<type 'str'>, <type 'int'>])
718
Sandro Tosi8b211fc2012-01-04 23:24:48 +0100719* ``'count'`` - This counts the number of times a keyword argument occurs. For
720 example, this is useful for increasing verbosity levels::
721
722 >>> parser = argparse.ArgumentParser()
723 >>> parser.add_argument('--verbose', '-v', action='count')
724 >>> parser.parse_args('-vvv'.split())
725 Namespace(verbose=3)
726
727* ``'help'`` - This prints a complete help message for all the options in the
728 current parser and then exits. By default a help action is automatically
729 added to the parser. See :class:`ArgumentParser` for details of how the
730 output is created.
731
Benjamin Petersona39e9662010-03-02 22:05:59 +0000732* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melottic69313a2011-04-22 01:29:13 +0300733 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujobb42f5e2012-02-20 02:08:01 +0100734 and exits when invoked::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000735
736 >>> import argparse
737 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000738 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
739 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000740 PROG 2.0
741
742You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000743the Action API. The easiest way to do this is to extend
744:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
745``__call__`` method should accept four parameters:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000746
747* ``parser`` - The ArgumentParser object which contains this action.
748
Éric Araujof0d44bc2011-07-29 17:59:17 +0200749* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300750 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
751 object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000752
Éric Araujo67719bd2011-08-19 02:00:07 +0200753* ``values`` - The associated command-line arguments, with any type conversions
754 applied. (Type conversions are specified with the type_ keyword argument to
Sandro Tosi682100e2012-08-12 10:49:07 +0200755 :meth:`~ArgumentParser.add_argument`.)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000756
757* ``option_string`` - The option string that was used to invoke this action.
758 The ``option_string`` argument is optional, and will be absent if the action
759 is associated with a positional argument.
760
Benjamin Peterson90c58022010-03-03 01:55:09 +0000761An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000762
763 >>> class FooAction(argparse.Action):
764 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000765 ... print '%r %r %r' % (namespace, values, option_string)
766 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000767 ...
768 >>> parser = argparse.ArgumentParser()
769 >>> parser.add_argument('--foo', action=FooAction)
770 >>> parser.add_argument('bar', action=FooAction)
771 >>> args = parser.parse_args('1 --foo 2'.split())
772 Namespace(bar=None, foo=None) '1' None
773 Namespace(bar='1', foo=None) '2' '--foo'
774 >>> args
775 Namespace(bar='1', foo='2')
776
777
778nargs
779^^^^^
780
781ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000782single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300783different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000784values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000785
Éric Araujobb42f5e2012-02-20 02:08:01 +0100786* ``N`` (an integer). ``N`` arguments from the command line will be gathered
787 together into a list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000788
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000789 >>> parser = argparse.ArgumentParser()
790 >>> parser.add_argument('--foo', nargs=2)
791 >>> parser.add_argument('bar', nargs=1)
792 >>> parser.parse_args('c --foo a b'.split())
793 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000794
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000795 Note that ``nargs=1`` produces a list of one item. This is different from
796 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000797
Éric Araujo67719bd2011-08-19 02:00:07 +0200798* ``'?'``. One argument will be consumed from the command line if possible, and
799 produced as a single item. If no command-line argument is present, the value from
Benjamin Petersona39e9662010-03-02 22:05:59 +0000800 default_ will be produced. Note that for optional arguments, there is an
801 additional case - the option string is present but not followed by a
Éric Araujo67719bd2011-08-19 02:00:07 +0200802 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Petersona39e9662010-03-02 22:05:59 +0000803 examples to illustrate this::
804
Georg Brandld2decd92010-03-02 22:17:38 +0000805 >>> parser = argparse.ArgumentParser()
806 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
807 >>> parser.add_argument('bar', nargs='?', default='d')
808 >>> parser.parse_args('XX --foo YY'.split())
809 Namespace(bar='XX', foo='YY')
810 >>> parser.parse_args('XX --foo'.split())
811 Namespace(bar='XX', foo='c')
812 >>> parser.parse_args(''.split())
813 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000814
Georg Brandld2decd92010-03-02 22:17:38 +0000815 One of the more common uses of ``nargs='?'`` is to allow optional input and
816 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000817
Georg Brandld2decd92010-03-02 22:17:38 +0000818 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000819 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
820 ... default=sys.stdin)
821 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
822 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000823 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000824 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
825 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000826 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000827 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
828 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000829
Éric Araujo67719bd2011-08-19 02:00:07 +0200830* ``'*'``. All command-line arguments present are gathered into a list. Note that
Georg Brandld2decd92010-03-02 22:17:38 +0000831 it generally doesn't make much sense to have more than one positional argument
832 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
833 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000834
Georg Brandld2decd92010-03-02 22:17:38 +0000835 >>> parser = argparse.ArgumentParser()
836 >>> parser.add_argument('--foo', nargs='*')
837 >>> parser.add_argument('--bar', nargs='*')
838 >>> parser.add_argument('baz', nargs='*')
839 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
840 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000841
842* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
843 list. Additionally, an error message will be generated if there wasn't at
Éric Araujo67719bd2011-08-19 02:00:07 +0200844 least one command-line argument present. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000845
Georg Brandld2decd92010-03-02 22:17:38 +0000846 >>> parser = argparse.ArgumentParser(prog='PROG')
847 >>> parser.add_argument('foo', nargs='+')
848 >>> parser.parse_args('a b'.split())
849 Namespace(foo=['a', 'b'])
850 >>> parser.parse_args(''.split())
851 usage: PROG [-h] foo [foo ...]
852 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000853
Sandro Tosicb212272012-01-19 22:22:35 +0100854* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
855 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujobb42f5e2012-02-20 02:08:01 +0100856 to other command line utilities::
Sandro Tosi10f047d2012-01-19 21:59:34 +0100857
858 >>> parser = argparse.ArgumentParser(prog='PROG')
859 >>> parser.add_argument('--foo')
860 >>> parser.add_argument('command')
861 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosicb212272012-01-19 22:22:35 +0100862 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
863 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi10f047d2012-01-19 21:59:34 +0100864
Éric Araujo67719bd2011-08-19 02:00:07 +0200865If the ``nargs`` keyword argument is not provided, the number of arguments consumed
866is determined by the action_. Generally this means a single command-line argument
Benjamin Petersona39e9662010-03-02 22:05:59 +0000867will be consumed and a single item (not a list) will be produced.
868
869
870const
871^^^^^
872
Ezio Melottic69313a2011-04-22 01:29:13 +0300873The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
874constant values that are not read from the command line but are required for
875the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000876
Ezio Melottic69313a2011-04-22 01:29:13 +0300877* When :meth:`~ArgumentParser.add_argument` is called with
878 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujobb42f5e2012-02-20 02:08:01 +0100879 ``const`` value to one of the attributes of the object returned by
880 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000881
Ezio Melottic69313a2011-04-22 01:29:13 +0300882* When :meth:`~ArgumentParser.add_argument` is called with option strings
883 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujo67719bd2011-08-19 02:00:07 +0200884 argument that can be followed by zero or one command-line arguments.
Ezio Melottic69313a2011-04-22 01:29:13 +0300885 When parsing the command line, if the option string is encountered with no
Éric Araujo67719bd2011-08-19 02:00:07 +0200886 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melottic69313a2011-04-22 01:29:13 +0300887 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000888
889The ``const`` keyword argument defaults to ``None``.
890
891
892default
893^^^^^^^
894
895All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300896command line. The ``default`` keyword argument of
897:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujo67719bd2011-08-19 02:00:07 +0200898specifies what value should be used if the command-line argument is not present.
Ezio Melottic69313a2011-04-22 01:29:13 +0300899For optional arguments, the ``default`` value is used when the option string
900was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000901
902 >>> parser = argparse.ArgumentParser()
903 >>> parser.add_argument('--foo', default=42)
904 >>> parser.parse_args('--foo 2'.split())
905 Namespace(foo='2')
906 >>> parser.parse_args(''.split())
907 Namespace(foo=42)
908
Éric Araujo67719bd2011-08-19 02:00:07 +0200909For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
910is used when no command-line argument was present::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000911
912 >>> parser = argparse.ArgumentParser()
913 >>> parser.add_argument('foo', nargs='?', default=42)
914 >>> parser.parse_args('a'.split())
915 Namespace(foo='a')
916 >>> parser.parse_args(''.split())
917 Namespace(foo=42)
918
919
Benjamin Peterson90c58022010-03-03 01:55:09 +0000920Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
921command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000922
923 >>> parser = argparse.ArgumentParser()
924 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
925 >>> parser.parse_args([])
926 Namespace()
927 >>> parser.parse_args(['--foo', '1'])
928 Namespace(foo='1')
929
930
931type
932^^^^
933
Éric Araujo67719bd2011-08-19 02:00:07 +0200934By default, :class:`ArgumentParser` objects read command-line arguments in as simple
935strings. However, quite often the command-line string should instead be
936interpreted as another type, like a :class:`float` or :class:`int`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300937``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujo67719bd2011-08-19 02:00:07 +0200938necessary type-checking and type conversions to be performed. Common built-in
939types and functions can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000940
941 >>> parser = argparse.ArgumentParser()
942 >>> parser.add_argument('foo', type=int)
943 >>> parser.add_argument('bar', type=file)
944 >>> parser.parse_args('2 temp.txt'.split())
945 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
946
947To ease the use of various types of files, the argparse module provides the
948factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000949``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000950writable file::
951
952 >>> parser = argparse.ArgumentParser()
953 >>> parser.add_argument('bar', type=argparse.FileType('w'))
954 >>> parser.parse_args(['out.txt'])
955 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
956
Benjamin Peterson90c58022010-03-03 01:55:09 +0000957``type=`` can take any callable that takes a single string argument and returns
Éric Araujo67719bd2011-08-19 02:00:07 +0200958the converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000959
960 >>> def perfect_square(string):
961 ... value = int(string)
962 ... sqrt = math.sqrt(value)
963 ... if sqrt != int(sqrt):
964 ... msg = "%r is not a perfect square" % string
965 ... raise argparse.ArgumentTypeError(msg)
966 ... return value
967 ...
968 >>> parser = argparse.ArgumentParser(prog='PROG')
969 >>> parser.add_argument('foo', type=perfect_square)
970 >>> parser.parse_args('9'.split())
971 Namespace(foo=9)
972 >>> parser.parse_args('7'.split())
973 usage: PROG [-h] foo
974 PROG: error: argument foo: '7' is not a perfect square
975
Benjamin Peterson90c58022010-03-03 01:55:09 +0000976The choices_ keyword argument may be more convenient for type checkers that
977simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000978
979 >>> parser = argparse.ArgumentParser(prog='PROG')
980 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
981 >>> parser.parse_args('7'.split())
982 Namespace(foo=7)
983 >>> parser.parse_args('11'.split())
984 usage: PROG [-h] {5,6,7,8,9}
985 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
986
987See the choices_ section for more details.
988
989
990choices
991^^^^^^^
992
Éric Araujo67719bd2011-08-19 02:00:07 +0200993Some command-line arguments should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000994These can be handled by passing a container object as the ``choices`` keyword
Ezio Melottic69313a2011-04-22 01:29:13 +0300995argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Éric Araujo67719bd2011-08-19 02:00:07 +0200996parsed, argument values will be checked, and an error message will be displayed if
997the argument was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000998
999 >>> parser = argparse.ArgumentParser(prog='PROG')
1000 >>> parser.add_argument('foo', choices='abc')
1001 >>> parser.parse_args('c'.split())
1002 Namespace(foo='c')
1003 >>> parser.parse_args('X'.split())
1004 usage: PROG [-h] {a,b,c}
1005 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
1006
1007Note that inclusion in the ``choices`` container is checked after any type_
1008conversions have been performed, so the type of the objects in the ``choices``
1009container should match the type_ specified::
1010
1011 >>> parser = argparse.ArgumentParser(prog='PROG')
1012 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
1013 >>> parser.parse_args('1j'.split())
1014 Namespace(foo=1j)
1015 >>> parser.parse_args('-- -4'.split())
1016 usage: PROG [-h] {1,1j}
1017 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
1018
1019Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +00001020value, so :class:`dict` objects, :class:`set` objects, custom containers,
1021etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001022
1023
1024required
1025^^^^^^^^
1026
Ezio Melotti01b600c2011-04-21 16:12:17 +03001027In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +03001028indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001029To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +03001030keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001031
1032 >>> parser = argparse.ArgumentParser()
1033 >>> parser.add_argument('--foo', required=True)
1034 >>> parser.parse_args(['--foo', 'BAR'])
1035 Namespace(foo='BAR')
1036 >>> parser.parse_args([])
1037 usage: argparse.py [-h] [--foo FOO]
1038 argparse.py: error: option --foo is required
1039
Ezio Melottic69313a2011-04-22 01:29:13 +03001040As the example shows, if an option is marked as ``required``,
1041:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1042present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001043
Benjamin Peterson90c58022010-03-03 01:55:09 +00001044.. note::
1045
1046 Required options are generally considered bad form because users expect
1047 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001048
1049
1050help
1051^^^^
1052
Benjamin Peterson90c58022010-03-03 01:55:09 +00001053The ``help`` value is a string containing a brief description of the argument.
1054When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001055command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001056argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001057
1058 >>> parser = argparse.ArgumentParser(prog='frobble')
1059 >>> parser.add_argument('--foo', action='store_true',
1060 ... help='foo the bars before frobbling')
1061 >>> parser.add_argument('bar', nargs='+',
1062 ... help='one of the bars to be frobbled')
1063 >>> parser.parse_args('-h'.split())
1064 usage: frobble [-h] [--foo] bar [bar ...]
1065
1066 positional arguments:
1067 bar one of the bars to be frobbled
1068
1069 optional arguments:
1070 -h, --help show this help message and exit
1071 --foo foo the bars before frobbling
1072
1073The ``help`` strings can include various format specifiers to avoid repetition
1074of things like the program name or the argument default_. The available
1075specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001076:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001077
1078 >>> parser = argparse.ArgumentParser(prog='frobble')
1079 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1080 ... help='the bar to %(prog)s (default: %(default)s)')
1081 >>> parser.print_help()
1082 usage: frobble [-h] [bar]
1083
1084 positional arguments:
1085 bar the bar to frobble (default: 42)
1086
1087 optional arguments:
1088 -h, --help show this help message and exit
1089
Sandro Tosi711f5472012-01-03 18:31:51 +01001090:mod:`argparse` supports silencing the help entry for certain options, by
1091setting the ``help`` value to ``argparse.SUPPRESS``::
1092
1093 >>> parser = argparse.ArgumentParser(prog='frobble')
1094 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1095 >>> parser.print_help()
1096 usage: frobble [-h]
1097
1098 optional arguments:
1099 -h, --help show this help message and exit
1100
Benjamin Petersona39e9662010-03-02 22:05:59 +00001101
1102metavar
1103^^^^^^^
1104
Benjamin Peterson90c58022010-03-03 01:55:09 +00001105When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001106to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001107value as the "name" of each object. By default, for positional argument
1108actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001109the dest_ value is uppercased. So, a single positional argument with
Eli Benderskybba1dd52011-11-11 16:42:11 +02001110``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujo67719bd2011-08-19 02:00:07 +02001111optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson90c58022010-03-03 01:55:09 +00001112will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001113
1114 >>> parser = argparse.ArgumentParser()
1115 >>> parser.add_argument('--foo')
1116 >>> parser.add_argument('bar')
1117 >>> parser.parse_args('X --foo Y'.split())
1118 Namespace(bar='X', foo='Y')
1119 >>> parser.print_help()
1120 usage: [-h] [--foo FOO] bar
1121
1122 positional arguments:
1123 bar
1124
1125 optional arguments:
1126 -h, --help show this help message and exit
1127 --foo FOO
1128
Benjamin Peterson90c58022010-03-03 01:55:09 +00001129An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001130
1131 >>> parser = argparse.ArgumentParser()
1132 >>> parser.add_argument('--foo', metavar='YYY')
1133 >>> parser.add_argument('bar', metavar='XXX')
1134 >>> parser.parse_args('X --foo Y'.split())
1135 Namespace(bar='X', foo='Y')
1136 >>> parser.print_help()
1137 usage: [-h] [--foo YYY] XXX
1138
1139 positional arguments:
1140 XXX
1141
1142 optional arguments:
1143 -h, --help show this help message and exit
1144 --foo YYY
1145
1146Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001147attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1148by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001149
1150Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001151Providing a tuple to ``metavar`` specifies a different display for each of the
1152arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001153
1154 >>> parser = argparse.ArgumentParser(prog='PROG')
1155 >>> parser.add_argument('-x', nargs=2)
1156 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1157 >>> parser.print_help()
1158 usage: PROG [-h] [-x X X] [--foo bar baz]
1159
1160 optional arguments:
1161 -h, --help show this help message and exit
1162 -x X X
1163 --foo bar baz
1164
1165
1166dest
1167^^^^
1168
Benjamin Peterson90c58022010-03-03 01:55:09 +00001169Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001170object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1171attribute is determined by the ``dest`` keyword argument of
1172:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1173``dest`` is normally supplied as the first argument to
1174:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001175
1176 >>> parser = argparse.ArgumentParser()
1177 >>> parser.add_argument('bar')
1178 >>> parser.parse_args('XXX'.split())
1179 Namespace(bar='XXX')
1180
1181For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001182the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo67719bd2011-08-19 02:00:07 +02001183taking the first long option string and stripping away the initial ``--``
Benjamin Petersona39e9662010-03-02 22:05:59 +00001184string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo67719bd2011-08-19 02:00:07 +02001185the first short option string by stripping the initial ``-`` character. Any
1186internal ``-`` characters will be converted to ``_`` characters to make sure
Georg Brandld2decd92010-03-02 22:17:38 +00001187the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001188behavior::
1189
1190 >>> parser = argparse.ArgumentParser()
1191 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1192 >>> parser.add_argument('-x', '-y')
1193 >>> parser.parse_args('-f 1 -x 2'.split())
1194 Namespace(foo_bar='1', x='2')
1195 >>> parser.parse_args('--foo 1 -y 2'.split())
1196 Namespace(foo_bar='1', x='2')
1197
Benjamin Peterson90c58022010-03-03 01:55:09 +00001198``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001199
1200 >>> parser = argparse.ArgumentParser()
1201 >>> parser.add_argument('--foo', dest='bar')
1202 >>> parser.parse_args('--foo XXX'.split())
1203 Namespace(bar='XXX')
1204
1205
1206The parse_args() method
1207-----------------------
1208
Georg Brandlb8d0e362010-11-26 07:53:50 +00001209.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001210
Benjamin Peterson90c58022010-03-03 01:55:09 +00001211 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001212 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001213
1214 Previous calls to :meth:`add_argument` determine exactly what objects are
1215 created and how they are assigned. See the documentation for
1216 :meth:`add_argument` for details.
1217
Éric Araujo67719bd2011-08-19 02:00:07 +02001218 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001219 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001220
Georg Brandlb8d0e362010-11-26 07:53:50 +00001221
Benjamin Petersona39e9662010-03-02 22:05:59 +00001222Option value syntax
1223^^^^^^^^^^^^^^^^^^^
1224
Ezio Melottic69313a2011-04-22 01:29:13 +03001225The :meth:`~ArgumentParser.parse_args` method supports several ways of
1226specifying the value of an option (if it takes one). In the simplest case, the
1227option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001228
1229 >>> parser = argparse.ArgumentParser(prog='PROG')
1230 >>> parser.add_argument('-x')
1231 >>> parser.add_argument('--foo')
1232 >>> parser.parse_args('-x X'.split())
1233 Namespace(foo=None, x='X')
1234 >>> parser.parse_args('--foo FOO'.split())
1235 Namespace(foo='FOO', x=None)
1236
Benjamin Peterson90c58022010-03-03 01:55:09 +00001237For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001238and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001239separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001240
1241 >>> parser.parse_args('--foo=FOO'.split())
1242 Namespace(foo='FOO', x=None)
1243
Benjamin Peterson90c58022010-03-03 01:55:09 +00001244For short options (options only one character long), the option and its value
1245can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001246
1247 >>> parser.parse_args('-xX'.split())
1248 Namespace(foo=None, x='X')
1249
Benjamin Peterson90c58022010-03-03 01:55:09 +00001250Several short options can be joined together, using only a single ``-`` prefix,
1251as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001252
1253 >>> parser = argparse.ArgumentParser(prog='PROG')
1254 >>> parser.add_argument('-x', action='store_true')
1255 >>> parser.add_argument('-y', action='store_true')
1256 >>> parser.add_argument('-z')
1257 >>> parser.parse_args('-xyzZ'.split())
1258 Namespace(x=True, y=True, z='Z')
1259
1260
1261Invalid arguments
1262^^^^^^^^^^^^^^^^^
1263
Ezio Melottic69313a2011-04-22 01:29:13 +03001264While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1265variety of errors, including ambiguous options, invalid types, invalid options,
1266wrong number of positional arguments, etc. When it encounters such an error,
1267it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001268
1269 >>> parser = argparse.ArgumentParser(prog='PROG')
1270 >>> parser.add_argument('--foo', type=int)
1271 >>> parser.add_argument('bar', nargs='?')
1272
1273 >>> # invalid type
1274 >>> parser.parse_args(['--foo', 'spam'])
1275 usage: PROG [-h] [--foo FOO] [bar]
1276 PROG: error: argument --foo: invalid int value: 'spam'
1277
1278 >>> # invalid option
1279 >>> parser.parse_args(['--bar'])
1280 usage: PROG [-h] [--foo FOO] [bar]
1281 PROG: error: no such option: --bar
1282
1283 >>> # wrong number of arguments
1284 >>> parser.parse_args(['spam', 'badger'])
1285 usage: PROG [-h] [--foo FOO] [bar]
1286 PROG: error: extra arguments found: badger
1287
1288
Éric Araujo67719bd2011-08-19 02:00:07 +02001289Arguments containing ``-``
1290^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001291
Ezio Melottic69313a2011-04-22 01:29:13 +03001292The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1293the user has clearly made a mistake, but some situations are inherently
Éric Araujo67719bd2011-08-19 02:00:07 +02001294ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melottic69313a2011-04-22 01:29:13 +03001295attempt to specify an option or an attempt to provide a positional argument.
1296The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo67719bd2011-08-19 02:00:07 +02001297arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melottic69313a2011-04-22 01:29:13 +03001298there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001299
1300 >>> parser = argparse.ArgumentParser(prog='PROG')
1301 >>> parser.add_argument('-x')
1302 >>> parser.add_argument('foo', nargs='?')
1303
1304 >>> # no negative number options, so -1 is a positional argument
1305 >>> parser.parse_args(['-x', '-1'])
1306 Namespace(foo=None, x='-1')
1307
1308 >>> # no negative number options, so -1 and -5 are positional arguments
1309 >>> parser.parse_args(['-x', '-1', '-5'])
1310 Namespace(foo='-5', x='-1')
1311
1312 >>> parser = argparse.ArgumentParser(prog='PROG')
1313 >>> parser.add_argument('-1', dest='one')
1314 >>> parser.add_argument('foo', nargs='?')
1315
1316 >>> # negative number options present, so -1 is an option
1317 >>> parser.parse_args(['-1', 'X'])
1318 Namespace(foo=None, one='X')
1319
1320 >>> # negative number options present, so -2 is an option
1321 >>> parser.parse_args(['-2'])
1322 usage: PROG [-h] [-1 ONE] [foo]
1323 PROG: error: no such option: -2
1324
1325 >>> # negative number options present, so both -1s are options
1326 >>> parser.parse_args(['-1', '-1'])
1327 usage: PROG [-h] [-1 ONE] [foo]
1328 PROG: error: argument -1: expected one argument
1329
Éric Araujo67719bd2011-08-19 02:00:07 +02001330If you have positional arguments that must begin with ``-`` and don't look
Benjamin Petersona39e9662010-03-02 22:05:59 +00001331like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001332:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1333argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001334
1335 >>> parser.parse_args(['--', '-f'])
1336 Namespace(foo='-f', one=None)
1337
1338
1339Argument abbreviations
1340^^^^^^^^^^^^^^^^^^^^^^
1341
Ezio Melottic69313a2011-04-22 01:29:13 +03001342The :meth:`~ArgumentParser.parse_args` method allows long options to be
1343abbreviated if the abbreviation is unambiguous::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001344
1345 >>> parser = argparse.ArgumentParser(prog='PROG')
1346 >>> parser.add_argument('-bacon')
1347 >>> parser.add_argument('-badger')
1348 >>> parser.parse_args('-bac MMM'.split())
1349 Namespace(bacon='MMM', badger=None)
1350 >>> parser.parse_args('-bad WOOD'.split())
1351 Namespace(bacon=None, badger='WOOD')
1352 >>> parser.parse_args('-ba BA'.split())
1353 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1354 PROG: error: ambiguous option: -ba could match -badger, -bacon
1355
Benjamin Peterson90c58022010-03-03 01:55:09 +00001356An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001357
1358
1359Beyond ``sys.argv``
1360^^^^^^^^^^^^^^^^^^^
1361
Éric Araujo67719bd2011-08-19 02:00:07 +02001362Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Georg Brandld2decd92010-03-02 22:17:38 +00001363of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001364:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1365interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001366
1367 >>> parser = argparse.ArgumentParser()
1368 >>> parser.add_argument(
1369 ... 'integers', metavar='int', type=int, choices=xrange(10),
1370 ... nargs='+', help='an integer in the range 0..9')
1371 >>> parser.add_argument(
1372 ... '--sum', dest='accumulate', action='store_const', const=sum,
1373 ... default=max, help='sum the integers (default: find the max)')
1374 >>> parser.parse_args(['1', '2', '3', '4'])
1375 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1376 >>> parser.parse_args('1 2 3 4 --sum'.split())
1377 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1378
1379
Steven Bethard3f69a052011-03-26 19:59:02 +01001380The Namespace object
1381^^^^^^^^^^^^^^^^^^^^
1382
Éric Araujof0d44bc2011-07-29 17:59:17 +02001383.. class:: Namespace
1384
1385 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1386 an object holding attributes and return it.
1387
1388This class is deliberately simple, just an :class:`object` subclass with a
1389readable string representation. If you prefer to have dict-like view of the
1390attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001391
1392 >>> parser = argparse.ArgumentParser()
1393 >>> parser.add_argument('--foo')
1394 >>> args = parser.parse_args(['--foo', 'BAR'])
1395 >>> vars(args)
1396 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001397
Benjamin Peterson90c58022010-03-03 01:55:09 +00001398It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001399already existing object, rather than a new :class:`Namespace` object. This can
1400be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001401
1402 >>> class C(object):
1403 ... pass
1404 ...
1405 >>> c = C()
1406 >>> parser = argparse.ArgumentParser()
1407 >>> parser.add_argument('--foo')
1408 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1409 >>> c.foo
1410 'BAR'
1411
1412
1413Other utilities
1414---------------
1415
1416Sub-commands
1417^^^^^^^^^^^^
1418
Benjamin Peterson90c58022010-03-03 01:55:09 +00001419.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001420
Benjamin Peterson90c58022010-03-03 01:55:09 +00001421 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001422 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001423 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001424 this way can be a particularly good idea when a program performs several
1425 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001426 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001427 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1428 called with no arguments and returns an special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001429 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1430 command name and any :class:`ArgumentParser` constructor arguments, and
1431 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001432
1433 Some example usage::
1434
1435 >>> # create the top-level parser
1436 >>> parser = argparse.ArgumentParser(prog='PROG')
1437 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1438 >>> subparsers = parser.add_subparsers(help='sub-command help')
1439 >>>
1440 >>> # create the parser for the "a" command
1441 >>> parser_a = subparsers.add_parser('a', help='a help')
1442 >>> parser_a.add_argument('bar', type=int, help='bar help')
1443 >>>
1444 >>> # create the parser for the "b" command
1445 >>> parser_b = subparsers.add_parser('b', help='b help')
1446 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1447 >>>
Éric Araujo67719bd2011-08-19 02:00:07 +02001448 >>> # parse some argument lists
Benjamin Petersona39e9662010-03-02 22:05:59 +00001449 >>> parser.parse_args(['a', '12'])
1450 Namespace(bar=12, foo=False)
1451 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1452 Namespace(baz='Z', foo=True)
1453
1454 Note that the object returned by :meth:`parse_args` will only contain
1455 attributes for the main parser and the subparser that was selected by the
1456 command line (and not any other subparsers). So in the example above, when
Éric Araujo67719bd2011-08-19 02:00:07 +02001457 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1458 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001459 ``baz`` attributes are present.
1460
1461 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001462 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001463 include parent parser or sibling parser messages. (A help message for each
1464 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001465 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001466
1467 ::
1468
1469 >>> parser.parse_args(['--help'])
1470 usage: PROG [-h] [--foo] {a,b} ...
1471
1472 positional arguments:
1473 {a,b} sub-command help
1474 a a help
1475 b b help
1476
1477 optional arguments:
1478 -h, --help show this help message and exit
1479 --foo foo help
1480
1481 >>> parser.parse_args(['a', '--help'])
1482 usage: PROG a [-h] bar
1483
1484 positional arguments:
1485 bar bar help
1486
1487 optional arguments:
1488 -h, --help show this help message and exit
1489
1490 >>> parser.parse_args(['b', '--help'])
1491 usage: PROG b [-h] [--baz {X,Y,Z}]
1492
1493 optional arguments:
1494 -h, --help show this help message and exit
1495 --baz {X,Y,Z} baz help
1496
Georg Brandld2decd92010-03-02 22:17:38 +00001497 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1498 keyword arguments. When either is present, the subparser's commands will
1499 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001500
1501 >>> parser = argparse.ArgumentParser()
1502 >>> subparsers = parser.add_subparsers(title='subcommands',
1503 ... description='valid subcommands',
1504 ... help='additional help')
1505 >>> subparsers.add_parser('foo')
1506 >>> subparsers.add_parser('bar')
1507 >>> parser.parse_args(['-h'])
1508 usage: [-h] {foo,bar} ...
1509
1510 optional arguments:
1511 -h, --help show this help message and exit
1512
1513 subcommands:
1514 valid subcommands
1515
1516 {foo,bar} additional help
1517
1518
Georg Brandld2decd92010-03-02 22:17:38 +00001519 One particularly effective way of handling sub-commands is to combine the use
1520 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1521 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001522 example::
1523
1524 >>> # sub-command functions
1525 >>> def foo(args):
1526 ... print args.x * args.y
1527 ...
1528 >>> def bar(args):
1529 ... print '((%s))' % args.z
1530 ...
1531 >>> # create the top-level parser
1532 >>> parser = argparse.ArgumentParser()
1533 >>> subparsers = parser.add_subparsers()
1534 >>>
1535 >>> # create the parser for the "foo" command
1536 >>> parser_foo = subparsers.add_parser('foo')
1537 >>> parser_foo.add_argument('-x', type=int, default=1)
1538 >>> parser_foo.add_argument('y', type=float)
1539 >>> parser_foo.set_defaults(func=foo)
1540 >>>
1541 >>> # create the parser for the "bar" command
1542 >>> parser_bar = subparsers.add_parser('bar')
1543 >>> parser_bar.add_argument('z')
1544 >>> parser_bar.set_defaults(func=bar)
1545 >>>
1546 >>> # parse the args and call whatever function was selected
1547 >>> args = parser.parse_args('foo 1 -x 2'.split())
1548 >>> args.func(args)
1549 2.0
1550 >>>
1551 >>> # parse the args and call whatever function was selected
1552 >>> args = parser.parse_args('bar XYZYX'.split())
1553 >>> args.func(args)
1554 ((XYZYX))
1555
Éric Araujobb42f5e2012-02-20 02:08:01 +01001556 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson90c58022010-03-03 01:55:09 +00001557 appropriate function after argument parsing is complete. Associating
1558 functions with actions like this is typically the easiest way to handle the
1559 different actions for each of your subparsers. However, if it is necessary
1560 to check the name of the subparser that was invoked, the ``dest`` keyword
1561 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001562
1563 >>> parser = argparse.ArgumentParser()
1564 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1565 >>> subparser1 = subparsers.add_parser('1')
1566 >>> subparser1.add_argument('-x')
1567 >>> subparser2 = subparsers.add_parser('2')
1568 >>> subparser2.add_argument('y')
1569 >>> parser.parse_args(['2', 'frobble'])
1570 Namespace(subparser_name='2', y='frobble')
1571
1572
1573FileType objects
1574^^^^^^^^^^^^^^^^
1575
1576.. class:: FileType(mode='r', bufsize=None)
1577
1578 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001579 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujo67719bd2011-08-19 02:00:07 +02001580 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujobb42f5e2012-02-20 02:08:01 +01001581 with the requested modes and buffer sizes::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001582
Éric Araujobb42f5e2012-02-20 02:08:01 +01001583 >>> parser = argparse.ArgumentParser()
1584 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1585 >>> parser.parse_args(['--output', 'out'])
1586 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001587
1588 FileType objects understand the pseudo-argument ``'-'`` and automatically
1589 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujobb42f5e2012-02-20 02:08:01 +01001590 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001591
Éric Araujobb42f5e2012-02-20 02:08:01 +01001592 >>> parser = argparse.ArgumentParser()
1593 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1594 >>> parser.parse_args(['-'])
1595 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001596
1597
1598Argument groups
1599^^^^^^^^^^^^^^^
1600
Georg Brandlb8d0e362010-11-26 07:53:50 +00001601.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001602
Benjamin Peterson90c58022010-03-03 01:55:09 +00001603 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001604 "positional arguments" and "optional arguments" when displaying help
1605 messages. When there is a better conceptual grouping of arguments than this
1606 default one, appropriate groups can be created using the
1607 :meth:`add_argument_group` method::
1608
1609 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1610 >>> group = parser.add_argument_group('group')
1611 >>> group.add_argument('--foo', help='foo help')
1612 >>> group.add_argument('bar', help='bar help')
1613 >>> parser.print_help()
1614 usage: PROG [--foo FOO] bar
1615
1616 group:
1617 bar bar help
1618 --foo FOO foo help
1619
1620 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001621 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1622 :class:`ArgumentParser`. When an argument is added to the group, the parser
1623 treats it just like a normal argument, but displays the argument in a
1624 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001625 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001626 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001627
1628 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1629 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1630 >>> group1.add_argument('foo', help='foo help')
1631 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1632 >>> group2.add_argument('--bar', help='bar help')
1633 >>> parser.print_help()
1634 usage: PROG [--bar BAR] foo
1635
1636 group1:
1637 group1 description
1638
1639 foo foo help
1640
1641 group2:
1642 group2 description
1643
1644 --bar BAR bar help
1645
Sandro Tosi48a88952012-03-26 19:35:52 +02001646 Note that any arguments not in your user-defined groups will end up back
1647 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001648
1649
1650Mutual exclusion
1651^^^^^^^^^^^^^^^^
1652
Georg Brandlb8d0e362010-11-26 07:53:50 +00001653.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001654
Ezio Melotti01b600c2011-04-21 16:12:17 +03001655 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1656 one of the arguments in the mutually exclusive group was present on the
1657 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001658
1659 >>> parser = argparse.ArgumentParser(prog='PROG')
1660 >>> group = parser.add_mutually_exclusive_group()
1661 >>> group.add_argument('--foo', action='store_true')
1662 >>> group.add_argument('--bar', action='store_false')
1663 >>> parser.parse_args(['--foo'])
1664 Namespace(bar=True, foo=True)
1665 >>> parser.parse_args(['--bar'])
1666 Namespace(bar=False, foo=False)
1667 >>> parser.parse_args(['--foo', '--bar'])
1668 usage: PROG [-h] [--foo | --bar]
1669 PROG: error: argument --bar: not allowed with argument --foo
1670
Georg Brandlb8d0e362010-11-26 07:53:50 +00001671 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001672 argument, to indicate that at least one of the mutually exclusive arguments
1673 is required::
1674
1675 >>> parser = argparse.ArgumentParser(prog='PROG')
1676 >>> group = parser.add_mutually_exclusive_group(required=True)
1677 >>> group.add_argument('--foo', action='store_true')
1678 >>> group.add_argument('--bar', action='store_false')
1679 >>> parser.parse_args([])
1680 usage: PROG [-h] (--foo | --bar)
1681 PROG: error: one of the arguments --foo --bar is required
1682
1683 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001684 *title* and *description* arguments of
1685 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001686
1687
1688Parser defaults
1689^^^^^^^^^^^^^^^
1690
Benjamin Peterson90c58022010-03-03 01:55:09 +00001691.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001692
Georg Brandld2decd92010-03-02 22:17:38 +00001693 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujo67719bd2011-08-19 02:00:07 +02001694 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001695 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001696 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001697 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001698
1699 >>> parser = argparse.ArgumentParser()
1700 >>> parser.add_argument('foo', type=int)
1701 >>> parser.set_defaults(bar=42, baz='badger')
1702 >>> parser.parse_args(['736'])
1703 Namespace(bar=42, baz='badger', foo=736)
1704
Benjamin Peterson90c58022010-03-03 01:55:09 +00001705 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001706
1707 >>> parser = argparse.ArgumentParser()
1708 >>> parser.add_argument('--foo', default='bar')
1709 >>> parser.set_defaults(foo='spam')
1710 >>> parser.parse_args([])
1711 Namespace(foo='spam')
1712
Benjamin Peterson90c58022010-03-03 01:55:09 +00001713 Parser-level defaults can be particularly useful when working with multiple
1714 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1715 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001716
Benjamin Peterson90c58022010-03-03 01:55:09 +00001717.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001718
1719 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001720 :meth:`~ArgumentParser.add_argument` or by
1721 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001722
1723 >>> parser = argparse.ArgumentParser()
1724 >>> parser.add_argument('--foo', default='badger')
1725 >>> parser.get_default('foo')
1726 'badger'
1727
1728
1729Printing help
1730^^^^^^^^^^^^^
1731
Ezio Melottic69313a2011-04-22 01:29:13 +03001732In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1733care of formatting and printing any usage or error messages. However, several
1734formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001735
Georg Brandlb8d0e362010-11-26 07:53:50 +00001736.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001737
1738 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001739 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001740 assumed.
1741
Georg Brandlb8d0e362010-11-26 07:53:50 +00001742.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001743
1744 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001745 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001746 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001747
1748There are also variants of these methods that simply return a string instead of
1749printing it:
1750
Georg Brandlb8d0e362010-11-26 07:53:50 +00001751.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001752
1753 Return a string containing a brief description of how the
1754 :class:`ArgumentParser` should be invoked on the command line.
1755
Georg Brandlb8d0e362010-11-26 07:53:50 +00001756.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001757
1758 Return a string containing a help message, including the program usage and
1759 information about the arguments registered with the :class:`ArgumentParser`.
1760
1761
Benjamin Petersona39e9662010-03-02 22:05:59 +00001762Partial parsing
1763^^^^^^^^^^^^^^^
1764
Georg Brandlb8d0e362010-11-26 07:53:50 +00001765.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001766
Ezio Melotti12125822011-04-16 23:04:51 +03001767Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001768the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001769:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001770:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1771extra arguments are present. Instead, it returns a two item tuple containing
1772the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001773
1774::
1775
1776 >>> parser = argparse.ArgumentParser()
1777 >>> parser.add_argument('--foo', action='store_true')
1778 >>> parser.add_argument('bar')
1779 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1780 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1781
1782
1783Customizing file parsing
1784^^^^^^^^^^^^^^^^^^^^^^^^
1785
Benjamin Peterson90c58022010-03-03 01:55:09 +00001786.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001787
Georg Brandlb8d0e362010-11-26 07:53:50 +00001788 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001789 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001790 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1791 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001792
Georg Brandlb8d0e362010-11-26 07:53:50 +00001793 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001794 the argument file. It returns a list of arguments parsed from this string.
1795 The method is called once per line read from the argument file, in order.
1796
Georg Brandld2decd92010-03-02 22:17:38 +00001797 A useful override of this method is one that treats each space-separated word
1798 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001799
1800 def convert_arg_line_to_args(self, arg_line):
1801 for arg in arg_line.split():
1802 if not arg.strip():
1803 continue
1804 yield arg
1805
1806
Georg Brandlb8d0e362010-11-26 07:53:50 +00001807Exiting methods
1808^^^^^^^^^^^^^^^
1809
1810.. method:: ArgumentParser.exit(status=0, message=None)
1811
1812 This method terminates the program, exiting with the specified *status*
1813 and, if given, it prints a *message* before that.
1814
1815.. method:: ArgumentParser.error(message)
1816
1817 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001818 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001819
1820
Georg Brandl58df6792010-07-03 10:25:47 +00001821.. _argparse-from-optparse:
1822
Benjamin Petersona39e9662010-03-02 22:05:59 +00001823Upgrading optparse code
1824-----------------------
1825
Ezio Melottic69313a2011-04-22 01:29:13 +03001826Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001827with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1828transparently, particularly with the changes required to support the new
1829``nargs=`` specifiers and better usage messages. When most everything in
1830:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1831longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001832
Ezio Melotti01b600c2011-04-21 16:12:17 +03001833A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001834
Ezio Melottic69313a2011-04-22 01:29:13 +03001835* Replace all :meth:`optparse.OptionParser.add_option` calls with
1836 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001837
R David Murray5080cad2012-03-30 18:09:07 -04001838* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001839 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5080cad2012-03-30 18:09:07 -04001840 calls for the positional arguments. Keep in mind that what was previously
1841 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001842
1843* Replace callback actions and the ``callback_*`` keyword arguments with
1844 ``type`` or ``action`` arguments.
1845
1846* Replace string names for ``type`` keyword arguments with the corresponding
1847 type objects (e.g. int, float, complex, etc).
1848
Benjamin Peterson90c58022010-03-03 01:55:09 +00001849* Replace :class:`optparse.Values` with :class:`Namespace` and
1850 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1851 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001852
Georg Brandld2decd92010-03-02 22:17:38 +00001853* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001854 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001855 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001856
1857* Replace the OptionParser constructor ``version`` argument with a call to
1858 ``parser.add_argument('--version', action='version', version='<the version>')``