blob: 83e8479192e3b71cd5e55dc120d00ac980ccde68 [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
Éric Araujobb42f5e2012-02-20 02:08:01 +0100133.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
134 [argument_default], [parents], [prefix_chars], \
135 [conflict_handler], [formatter_class])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000136
Georg Brandld2decd92010-03-02 22:17:38 +0000137 Create a new :class:`ArgumentParser` object. Each parameter has its own more
Benjamin Petersona39e9662010-03-02 22:05:59 +0000138 detailed description below, but in short they are:
139
140 * description_ - Text to display before the argument help.
141
142 * epilog_ - Text to display after the argument help.
143
Benjamin Peterson90c58022010-03-03 01:55:09 +0000144 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000145
146 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000147 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000148
Benjamin Peterson90c58022010-03-03 01:55:09 +0000149 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Petersona39e9662010-03-02 22:05:59 +0000150 also be included.
151
152 * prefix_chars_ - The set of characters that prefix optional arguments.
153 (default: '-')
154
155 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson90c58022010-03-03 01:55:09 +0000156 which additional arguments should be read. (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000157
158 * formatter_class_ - A class for customizing the help output.
159
160 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
161 conflicting optionals.
162
Benjamin Peterson90c58022010-03-03 01:55:09 +0000163 * prog_ - The name of the program (default:
Éric Araujo7ce05e02011-09-01 19:54:05 +0200164 ``sys.argv[0]``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000165
Benjamin Peterson90c58022010-03-03 01:55:09 +0000166 * usage_ - The string describing the program usage (default: generated)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000167
Benjamin Peterson90c58022010-03-03 01:55:09 +0000168The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000169
170
171description
172^^^^^^^^^^^
173
Benjamin Peterson90c58022010-03-03 01:55:09 +0000174Most calls to the :class:`ArgumentParser` constructor will use the
175``description=`` keyword argument. This argument gives a brief description of
176what the program does and how it works. In help messages, the description is
177displayed between the command-line usage string and the help messages for the
178various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000179
180 >>> parser = argparse.ArgumentParser(description='A foo that bars')
181 >>> parser.print_help()
182 usage: argparse.py [-h]
183
184 A foo that bars
185
186 optional arguments:
187 -h, --help show this help message and exit
188
189By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000190given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000191
192
193epilog
194^^^^^^
195
196Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000197description of the arguments. Such text can be specified using the ``epilog=``
198argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000199
200 >>> parser = argparse.ArgumentParser(
201 ... description='A foo that bars',
202 ... epilog="And that's how you'd foo a bar")
203 >>> parser.print_help()
204 usage: argparse.py [-h]
205
206 A foo that bars
207
208 optional arguments:
209 -h, --help show this help message and exit
210
211 And that's how you'd foo a bar
212
213As with the description_ argument, the ``epilog=`` text is by default
214line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000215argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000216
217
218add_help
219^^^^^^^^
220
R. David Murray1cbf78e2010-08-03 18:14:01 +0000221By default, ArgumentParser objects add an option which simply displays
222the parser's help message. For example, consider a file named
Benjamin Petersona39e9662010-03-02 22:05:59 +0000223``myprogram.py`` containing the following code::
224
225 import argparse
226 parser = argparse.ArgumentParser()
227 parser.add_argument('--foo', help='foo help')
228 args = parser.parse_args()
229
Ezio Melotti12125822011-04-16 23:04:51 +0300230If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Petersona39e9662010-03-02 22:05:59 +0000231help will be printed::
232
233 $ python myprogram.py --help
234 usage: myprogram.py [-h] [--foo FOO]
235
236 optional arguments:
237 -h, --help show this help message and exit
238 --foo FOO foo help
239
240Occasionally, it may be useful to disable the addition of this help option.
241This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson90c58022010-03-03 01:55:09 +0000242:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000243
244 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
245 >>> parser.add_argument('--foo', help='foo help')
246 >>> parser.print_help()
247 usage: PROG [--foo FOO]
248
249 optional arguments:
250 --foo FOO foo help
251
R. David Murray1cbf78e2010-08-03 18:14:01 +0000252The help option is typically ``-h/--help``. The exception to this is
Éric Araujo67719bd2011-08-19 02:00:07 +0200253if the ``prefix_chars=`` is specified and does not include ``-``, in
R. David Murray1cbf78e2010-08-03 18:14:01 +0000254which case ``-h`` and ``--help`` are not valid options. In
255this case, the first character in ``prefix_chars`` is used to prefix
256the help options::
257
258 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
259 >>> parser.print_help()
260 usage: PROG [+h]
261
262 optional arguments:
263 +h, ++help show this help message and exit
264
265
Benjamin Petersona39e9662010-03-02 22:05:59 +0000266prefix_chars
267^^^^^^^^^^^^
268
Éric Araujo67719bd2011-08-19 02:00:07 +0200269Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
R. David Murray1cbf78e2010-08-03 18:14:01 +0000270Parsers that need to support different or additional prefix
271characters, e.g. for options
Benjamin Petersona39e9662010-03-02 22:05:59 +0000272like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
273to the ArgumentParser constructor::
274
275 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
276 >>> parser.add_argument('+f')
277 >>> parser.add_argument('++bar')
278 >>> parser.parse_args('+f X ++bar Y'.split())
279 Namespace(bar='Y', f='X')
280
281The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
Éric Araujo67719bd2011-08-19 02:00:07 +0200282characters that does not include ``-`` will cause ``-f/--foo`` options to be
Benjamin Petersona39e9662010-03-02 22:05:59 +0000283disallowed.
284
285
286fromfile_prefix_chars
287^^^^^^^^^^^^^^^^^^^^^
288
Benjamin Peterson90c58022010-03-03 01:55:09 +0000289Sometimes, for example when dealing with a particularly long argument lists, it
290may make sense to keep the list of arguments in a file rather than typing it out
291at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
292:class:`ArgumentParser` constructor, then arguments that start with any of the
293specified characters will be treated as files, and will be replaced by the
294arguments they contain. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000295
Benjamin Peterson90c58022010-03-03 01:55:09 +0000296 >>> with open('args.txt', 'w') as fp:
297 ... fp.write('-f\nbar')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000298 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
299 >>> parser.add_argument('-f')
300 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
301 Namespace(f='bar')
302
303Arguments read from a file must by default be one per line (but see also
Ezio Melottic69313a2011-04-22 01:29:13 +0300304:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
305were in the same place as the original file referencing argument on the command
306line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
307is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000308
309The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
310arguments will never be treated as file references.
311
Georg Brandlb8d0e362010-11-26 07:53:50 +0000312
Benjamin Petersona39e9662010-03-02 22:05:59 +0000313argument_default
314^^^^^^^^^^^^^^^^
315
316Generally, argument defaults are specified either by passing a default to
Ezio Melottic69313a2011-04-22 01:29:13 +0300317:meth:`~ArgumentParser.add_argument` or by calling the
318:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
319pairs. Sometimes however, it may be useful to specify a single parser-wide
320default for arguments. This can be accomplished by passing the
321``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
322to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson90c58022010-03-03 01:55:09 +0000323calls, we supply ``argument_default=SUPPRESS``::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000324
325 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
326 >>> parser.add_argument('--foo')
327 >>> parser.add_argument('bar', nargs='?')
328 >>> parser.parse_args(['--foo', '1', 'BAR'])
329 Namespace(bar='BAR', foo='1')
330 >>> parser.parse_args([])
331 Namespace()
332
333
334parents
335^^^^^^^
336
337Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000338repeating the definitions of these arguments, a single parser with all the
339shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
340can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
341objects, collects all the positional and optional actions from them, and adds
342these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000343
344 >>> parent_parser = argparse.ArgumentParser(add_help=False)
345 >>> parent_parser.add_argument('--parent', type=int)
346
347 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
348 >>> foo_parser.add_argument('foo')
349 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
350 Namespace(foo='XXX', parent=2)
351
352 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
353 >>> bar_parser.add_argument('--bar')
354 >>> bar_parser.parse_args(['--bar', 'YYY'])
355 Namespace(bar='YYY', parent=None)
356
Georg Brandld2decd92010-03-02 22:17:38 +0000357Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000358:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
359and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000360
Steven Bethard5e0062d2011-03-26 21:50:38 +0100361.. note::
362 You must fully initialize the parsers before passing them via ``parents=``.
363 If you change the parent parsers after the child parser, those changes will
364 not be reflected in the child.
365
Benjamin Petersona39e9662010-03-02 22:05:59 +0000366
367formatter_class
368^^^^^^^^^^^^^^^
369
Benjamin Peterson90c58022010-03-03 01:55:09 +0000370:class:`ArgumentParser` objects allow the help formatting to be customized by
371specifying an alternate formatting class. Currently, there are three such
Ezio Melottic69313a2011-04-22 01:29:13 +0300372classes:
373
374.. class:: RawDescriptionHelpFormatter
375 RawTextHelpFormatter
376 ArgumentDefaultsHelpFormatter
377
378The first two allow more control over how textual descriptions are displayed,
379while the last automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000380
Benjamin Peterson90c58022010-03-03 01:55:09 +0000381By default, :class:`ArgumentParser` objects line-wrap the description_ and
382epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000383
384 >>> parser = argparse.ArgumentParser(
385 ... prog='PROG',
386 ... description='''this description
387 ... was indented weird
388 ... but that is okay''',
389 ... epilog='''
390 ... likewise for this epilog whose whitespace will
391 ... be cleaned up and whose words will be wrapped
392 ... across a couple lines''')
393 >>> parser.print_help()
394 usage: PROG [-h]
395
396 this description was indented weird but that is okay
397
398 optional arguments:
399 -h, --help show this help message and exit
400
401 likewise for this epilog whose whitespace will be cleaned up and whose words
402 will be wrapped across a couple lines
403
Éric Araujo67719bd2011-08-19 02:00:07 +0200404Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000405indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000406should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000407
408 >>> parser = argparse.ArgumentParser(
409 ... prog='PROG',
410 ... formatter_class=argparse.RawDescriptionHelpFormatter,
411 ... description=textwrap.dedent('''\
412 ... Please do not mess up this text!
413 ... --------------------------------
414 ... I have indented it
415 ... exactly the way
416 ... I want it
417 ... '''))
418 >>> parser.print_help()
419 usage: PROG [-h]
420
421 Please do not mess up this text!
422 --------------------------------
423 I have indented it
424 exactly the way
425 I want it
426
427 optional arguments:
428 -h, --help show this help message and exit
429
Éric Araujo67719bd2011-08-19 02:00:07 +0200430:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson90c58022010-03-03 01:55:09 +0000431including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000432
Benjamin Peterson90c58022010-03-03 01:55:09 +0000433The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000434will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000435
436 >>> parser = argparse.ArgumentParser(
437 ... prog='PROG',
438 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
439 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
440 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
441 >>> parser.print_help()
442 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
443
444 positional arguments:
445 bar BAR! (default: [1, 2, 3])
446
447 optional arguments:
448 -h, --help show this help message and exit
449 --foo FOO FOO! (default: 42)
450
451
452conflict_handler
453^^^^^^^^^^^^^^^^
454
Benjamin Peterson90c58022010-03-03 01:55:09 +0000455:class:`ArgumentParser` objects do not allow two actions with the same option
456string. By default, :class:`ArgumentParser` objects raises an exception if an
457attempt is made to create an argument with an option string that is already in
458use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000459
460 >>> parser = argparse.ArgumentParser(prog='PROG')
461 >>> parser.add_argument('-f', '--foo', help='old foo help')
462 >>> parser.add_argument('--foo', help='new foo help')
463 Traceback (most recent call last):
464 ..
465 ArgumentError: argument --foo: conflicting option string(s): --foo
466
467Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000468older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000469``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000470:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000471
472 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
473 >>> parser.add_argument('-f', '--foo', help='old foo help')
474 >>> parser.add_argument('--foo', help='new foo help')
475 >>> parser.print_help()
476 usage: PROG [-h] [-f FOO] [--foo FOO]
477
478 optional arguments:
479 -h, --help show this help message and exit
480 -f FOO old foo help
481 --foo FOO new foo help
482
Benjamin Peterson90c58022010-03-03 01:55:09 +0000483Note that :class:`ArgumentParser` objects only remove an action if all of its
484option strings are overridden. So, in the example above, the old ``-f/--foo``
485action is retained as the ``-f`` action, because only the ``--foo`` option
486string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000487
488
489prog
490^^^^
491
Benjamin Peterson90c58022010-03-03 01:55:09 +0000492By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
493how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000494always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000495invoked on the command line. For example, consider a file named
496``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000497
498 import argparse
499 parser = argparse.ArgumentParser()
500 parser.add_argument('--foo', help='foo help')
501 args = parser.parse_args()
502
503The help for this program will display ``myprogram.py`` as the program name
504(regardless of where the program was invoked from)::
505
506 $ python myprogram.py --help
507 usage: myprogram.py [-h] [--foo FOO]
508
509 optional arguments:
510 -h, --help show this help message and exit
511 --foo FOO foo help
512 $ cd ..
513 $ python subdir\myprogram.py --help
514 usage: myprogram.py [-h] [--foo FOO]
515
516 optional arguments:
517 -h, --help show this help message and exit
518 --foo FOO foo help
519
520To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000521``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000522
523 >>> parser = argparse.ArgumentParser(prog='myprogram')
524 >>> parser.print_help()
525 usage: myprogram [-h]
526
527 optional arguments:
528 -h, --help show this help message and exit
529
530Note that the program name, whether determined from ``sys.argv[0]`` or from the
531``prog=`` argument, is available to help messages using the ``%(prog)s`` format
532specifier.
533
534::
535
536 >>> parser = argparse.ArgumentParser(prog='myprogram')
537 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
538 >>> parser.print_help()
539 usage: myprogram [-h] [--foo FOO]
540
541 optional arguments:
542 -h, --help show this help message and exit
543 --foo FOO foo of the myprogram program
544
545
546usage
547^^^^^
548
Benjamin Peterson90c58022010-03-03 01:55:09 +0000549By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000550arguments it contains::
551
552 >>> parser = argparse.ArgumentParser(prog='PROG')
553 >>> parser.add_argument('--foo', nargs='?', help='foo help')
554 >>> parser.add_argument('bar', nargs='+', help='bar help')
555 >>> parser.print_help()
556 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
557
558 positional arguments:
559 bar bar help
560
561 optional arguments:
562 -h, --help show this help message and exit
563 --foo [FOO] foo help
564
Benjamin Peterson90c58022010-03-03 01:55:09 +0000565The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000566
567 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
568 >>> parser.add_argument('--foo', nargs='?', help='foo help')
569 >>> parser.add_argument('bar', nargs='+', help='bar help')
570 >>> parser.print_help()
571 usage: PROG [options]
572
573 positional arguments:
574 bar bar help
575
576 optional arguments:
577 -h, --help show this help message and exit
578 --foo [FOO] foo help
579
Benjamin Peterson90c58022010-03-03 01:55:09 +0000580The ``%(prog)s`` format specifier is available to fill in the program name in
581your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000582
583
584The add_argument() method
585-------------------------
586
Éric Araujobb42f5e2012-02-20 02:08:01 +0100587.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
588 [const], [default], [type], [choices], [required], \
589 [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000590
Ezio Melotti12125822011-04-16 23:04:51 +0300591 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000592 has its own more detailed description below, but in short they are:
593
594 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300595 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000596
597 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300598 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000599
600 * nargs_ - The number of command-line arguments that should be consumed.
601
602 * const_ - A constant value required by some action_ and nargs_ selections.
603
604 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300605 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000606
Ezio Melotti12125822011-04-16 23:04:51 +0300607 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000608
609 * choices_ - A container of the allowable values for the argument.
610
611 * required_ - Whether or not the command-line option may be omitted
612 (optionals only).
613
614 * help_ - A brief description of what the argument does.
615
616 * metavar_ - A name for the argument in usage messages.
617
618 * dest_ - The name of the attribute to be added to the object returned by
619 :meth:`parse_args`.
620
Benjamin Peterson90c58022010-03-03 01:55:09 +0000621The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000622
Georg Brandlb8d0e362010-11-26 07:53:50 +0000623
Benjamin Petersona39e9662010-03-02 22:05:59 +0000624name or flags
625^^^^^^^^^^^^^
626
Ezio Melottic69313a2011-04-22 01:29:13 +0300627The :meth:`~ArgumentParser.add_argument` method must know whether an optional
628argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
629filenames, is expected. The first arguments passed to
630:meth:`~ArgumentParser.add_argument` must therefore be either a series of
631flags, or a simple argument name. For example, an optional argument could
632be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000633
634 >>> parser.add_argument('-f', '--foo')
635
636while a positional argument could be created like::
637
638 >>> parser.add_argument('bar')
639
Ezio Melottic69313a2011-04-22 01:29:13 +0300640When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
641identified by the ``-`` prefix, and the remaining arguments will be assumed to
642be positional::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000643
644 >>> parser = argparse.ArgumentParser(prog='PROG')
645 >>> parser.add_argument('-f', '--foo')
646 >>> parser.add_argument('bar')
647 >>> parser.parse_args(['BAR'])
648 Namespace(bar='BAR', foo=None)
649 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
650 Namespace(bar='BAR', foo='FOO')
651 >>> parser.parse_args(['--foo', 'FOO'])
652 usage: PROG [-h] [-f FOO] bar
653 PROG: error: too few arguments
654
Georg Brandlb8d0e362010-11-26 07:53:50 +0000655
Benjamin Petersona39e9662010-03-02 22:05:59 +0000656action
657^^^^^^
658
Éric Araujo67719bd2011-08-19 02:00:07 +0200659:class:`ArgumentParser` objects associate command-line arguments with actions. These
660actions can do just about anything with the command-line arguments associated with
Benjamin Petersona39e9662010-03-02 22:05:59 +0000661them, though most actions simply add an attribute to the object returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300662:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Éric Araujo67719bd2011-08-19 02:00:07 +0200663how the command-line arguments should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000664
Georg Brandld2decd92010-03-02 22:17:38 +0000665* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300666 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000667
668 >>> parser = argparse.ArgumentParser()
669 >>> parser.add_argument('--foo')
670 >>> parser.parse_args('--foo 1'.split())
671 Namespace(foo='1')
672
673* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti310619c2011-04-21 23:06:48 +0300674 argument. (Note that the const_ keyword argument defaults to the rather
675 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
676 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000677
678 >>> parser = argparse.ArgumentParser()
679 >>> parser.add_argument('--foo', action='store_const', const=42)
680 >>> parser.parse_args('--foo'.split())
681 Namespace(foo=42)
682
Raymond Hettinger421467f2011-11-20 11:05:23 -0800683* ``'store_true'`` and ``'store_false'`` - These are special cases of
684 ``'store_const'`` using for storing the values ``True`` and ``False``
685 respectively. In addition, they create default values of *False* and *True*
686 respectively. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000687
688 >>> parser = argparse.ArgumentParser()
689 >>> parser.add_argument('--foo', action='store_true')
690 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettinger421467f2011-11-20 11:05:23 -0800691 >>> parser.add_argument('--baz', action='store_false')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000692 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettinger421467f2011-11-20 11:05:23 -0800693 Namespace(bar=False, baz=True, foo=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000694
695* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000696 list. This is useful to allow an option to be specified multiple times.
697 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000698
699 >>> parser = argparse.ArgumentParser()
700 >>> parser.add_argument('--foo', action='append')
701 >>> parser.parse_args('--foo 1 --foo 2'.split())
702 Namespace(foo=['1', '2'])
703
704* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000705 the const_ keyword argument to the list. (Note that the const_ keyword
706 argument defaults to ``None``.) The ``'append_const'`` action is typically
707 useful when multiple arguments need to store constants to the same list. For
708 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000709
710 >>> parser = argparse.ArgumentParser()
711 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
712 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
713 >>> parser.parse_args('--str --int'.split())
714 Namespace(types=[<type 'str'>, <type 'int'>])
715
Sandro Tosi8b211fc2012-01-04 23:24:48 +0100716* ``'count'`` - This counts the number of times a keyword argument occurs. For
717 example, this is useful for increasing verbosity levels::
718
719 >>> parser = argparse.ArgumentParser()
720 >>> parser.add_argument('--verbose', '-v', action='count')
721 >>> parser.parse_args('-vvv'.split())
722 Namespace(verbose=3)
723
724* ``'help'`` - This prints a complete help message for all the options in the
725 current parser and then exits. By default a help action is automatically
726 added to the parser. See :class:`ArgumentParser` for details of how the
727 output is created.
728
Benjamin Petersona39e9662010-03-02 22:05:59 +0000729* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melottic69313a2011-04-22 01:29:13 +0300730 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujobb42f5e2012-02-20 02:08:01 +0100731 and exits when invoked::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000732
733 >>> import argparse
734 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000735 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
736 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000737 PROG 2.0
738
739You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000740the Action API. The easiest way to do this is to extend
741:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
742``__call__`` method should accept four parameters:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000743
744* ``parser`` - The ArgumentParser object which contains this action.
745
Éric Araujof0d44bc2011-07-29 17:59:17 +0200746* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300747 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
748 object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000749
Éric Araujo67719bd2011-08-19 02:00:07 +0200750* ``values`` - The associated command-line arguments, with any type conversions
751 applied. (Type conversions are specified with the type_ keyword argument to
Ezio Melottic69313a2011-04-22 01:29:13 +0300752 :meth:`~ArgumentParser.add_argument`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000753
754* ``option_string`` - The option string that was used to invoke this action.
755 The ``option_string`` argument is optional, and will be absent if the action
756 is associated with a positional argument.
757
Benjamin Peterson90c58022010-03-03 01:55:09 +0000758An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000759
760 >>> class FooAction(argparse.Action):
761 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000762 ... print '%r %r %r' % (namespace, values, option_string)
763 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000764 ...
765 >>> parser = argparse.ArgumentParser()
766 >>> parser.add_argument('--foo', action=FooAction)
767 >>> parser.add_argument('bar', action=FooAction)
768 >>> args = parser.parse_args('1 --foo 2'.split())
769 Namespace(bar=None, foo=None) '1' None
770 Namespace(bar='1', foo=None) '2' '--foo'
771 >>> args
772 Namespace(bar='1', foo='2')
773
774
775nargs
776^^^^^
777
778ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000779single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300780different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000781values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000782
Éric Araujobb42f5e2012-02-20 02:08:01 +0100783* ``N`` (an integer). ``N`` arguments from the command line will be gathered
784 together into a list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000785
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000786 >>> parser = argparse.ArgumentParser()
787 >>> parser.add_argument('--foo', nargs=2)
788 >>> parser.add_argument('bar', nargs=1)
789 >>> parser.parse_args('c --foo a b'.split())
790 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000791
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000792 Note that ``nargs=1`` produces a list of one item. This is different from
793 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000794
Éric Araujo67719bd2011-08-19 02:00:07 +0200795* ``'?'``. One argument will be consumed from the command line if possible, and
796 produced as a single item. If no command-line argument is present, the value from
Benjamin Petersona39e9662010-03-02 22:05:59 +0000797 default_ will be produced. Note that for optional arguments, there is an
798 additional case - the option string is present but not followed by a
Éric Araujo67719bd2011-08-19 02:00:07 +0200799 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Petersona39e9662010-03-02 22:05:59 +0000800 examples to illustrate this::
801
Georg Brandld2decd92010-03-02 22:17:38 +0000802 >>> parser = argparse.ArgumentParser()
803 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
804 >>> parser.add_argument('bar', nargs='?', default='d')
805 >>> parser.parse_args('XX --foo YY'.split())
806 Namespace(bar='XX', foo='YY')
807 >>> parser.parse_args('XX --foo'.split())
808 Namespace(bar='XX', foo='c')
809 >>> parser.parse_args(''.split())
810 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000811
Georg Brandld2decd92010-03-02 22:17:38 +0000812 One of the more common uses of ``nargs='?'`` is to allow optional input and
813 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000814
Georg Brandld2decd92010-03-02 22:17:38 +0000815 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000816 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
817 ... default=sys.stdin)
818 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
819 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000820 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000821 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
822 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000823 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000824 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
825 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000826
Éric Araujo67719bd2011-08-19 02:00:07 +0200827* ``'*'``. All command-line arguments present are gathered into a list. Note that
Georg Brandld2decd92010-03-02 22:17:38 +0000828 it generally doesn't make much sense to have more than one positional argument
829 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
830 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000831
Georg Brandld2decd92010-03-02 22:17:38 +0000832 >>> parser = argparse.ArgumentParser()
833 >>> parser.add_argument('--foo', nargs='*')
834 >>> parser.add_argument('--bar', nargs='*')
835 >>> parser.add_argument('baz', nargs='*')
836 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
837 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000838
839* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
840 list. Additionally, an error message will be generated if there wasn't at
Éric Araujo67719bd2011-08-19 02:00:07 +0200841 least one command-line argument present. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000842
Georg Brandld2decd92010-03-02 22:17:38 +0000843 >>> parser = argparse.ArgumentParser(prog='PROG')
844 >>> parser.add_argument('foo', nargs='+')
845 >>> parser.parse_args('a b'.split())
846 Namespace(foo=['a', 'b'])
847 >>> parser.parse_args(''.split())
848 usage: PROG [-h] foo [foo ...]
849 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000850
Sandro Tosicb212272012-01-19 22:22:35 +0100851* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
852 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujobb42f5e2012-02-20 02:08:01 +0100853 to other command line utilities::
Sandro Tosi10f047d2012-01-19 21:59:34 +0100854
855 >>> parser = argparse.ArgumentParser(prog='PROG')
856 >>> parser.add_argument('--foo')
857 >>> parser.add_argument('command')
858 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosicb212272012-01-19 22:22:35 +0100859 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
860 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi10f047d2012-01-19 21:59:34 +0100861
Éric Araujo67719bd2011-08-19 02:00:07 +0200862If the ``nargs`` keyword argument is not provided, the number of arguments consumed
863is determined by the action_. Generally this means a single command-line argument
Benjamin Petersona39e9662010-03-02 22:05:59 +0000864will be consumed and a single item (not a list) will be produced.
865
866
867const
868^^^^^
869
Ezio Melottic69313a2011-04-22 01:29:13 +0300870The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
871constant values that are not read from the command line but are required for
872the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000873
Ezio Melottic69313a2011-04-22 01:29:13 +0300874* When :meth:`~ArgumentParser.add_argument` is called with
875 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujobb42f5e2012-02-20 02:08:01 +0100876 ``const`` value to one of the attributes of the object returned by
877 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000878
Ezio Melottic69313a2011-04-22 01:29:13 +0300879* When :meth:`~ArgumentParser.add_argument` is called with option strings
880 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujo67719bd2011-08-19 02:00:07 +0200881 argument that can be followed by zero or one command-line arguments.
Ezio Melottic69313a2011-04-22 01:29:13 +0300882 When parsing the command line, if the option string is encountered with no
Éric Araujo67719bd2011-08-19 02:00:07 +0200883 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melottic69313a2011-04-22 01:29:13 +0300884 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000885
886The ``const`` keyword argument defaults to ``None``.
887
888
889default
890^^^^^^^
891
892All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300893command line. The ``default`` keyword argument of
894:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujo67719bd2011-08-19 02:00:07 +0200895specifies what value should be used if the command-line argument is not present.
Ezio Melottic69313a2011-04-22 01:29:13 +0300896For optional arguments, the ``default`` value is used when the option string
897was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000898
899 >>> parser = argparse.ArgumentParser()
900 >>> parser.add_argument('--foo', default=42)
901 >>> parser.parse_args('--foo 2'.split())
902 Namespace(foo='2')
903 >>> parser.parse_args(''.split())
904 Namespace(foo=42)
905
Éric Araujo67719bd2011-08-19 02:00:07 +0200906For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
907is used when no command-line argument was present::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000908
909 >>> parser = argparse.ArgumentParser()
910 >>> parser.add_argument('foo', nargs='?', default=42)
911 >>> parser.parse_args('a'.split())
912 Namespace(foo='a')
913 >>> parser.parse_args(''.split())
914 Namespace(foo=42)
915
916
Benjamin Peterson90c58022010-03-03 01:55:09 +0000917Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
918command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000919
920 >>> parser = argparse.ArgumentParser()
921 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
922 >>> parser.parse_args([])
923 Namespace()
924 >>> parser.parse_args(['--foo', '1'])
925 Namespace(foo='1')
926
927
928type
929^^^^
930
Éric Araujo67719bd2011-08-19 02:00:07 +0200931By default, :class:`ArgumentParser` objects read command-line arguments in as simple
932strings. However, quite often the command-line string should instead be
933interpreted as another type, like a :class:`float` or :class:`int`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300934``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujo67719bd2011-08-19 02:00:07 +0200935necessary type-checking and type conversions to be performed. Common built-in
936types and functions can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000937
938 >>> parser = argparse.ArgumentParser()
939 >>> parser.add_argument('foo', type=int)
940 >>> parser.add_argument('bar', type=file)
941 >>> parser.parse_args('2 temp.txt'.split())
942 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
943
944To ease the use of various types of files, the argparse module provides the
945factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000946``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000947writable file::
948
949 >>> parser = argparse.ArgumentParser()
950 >>> parser.add_argument('bar', type=argparse.FileType('w'))
951 >>> parser.parse_args(['out.txt'])
952 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
953
Benjamin Peterson90c58022010-03-03 01:55:09 +0000954``type=`` can take any callable that takes a single string argument and returns
Éric Araujo67719bd2011-08-19 02:00:07 +0200955the converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000956
957 >>> def perfect_square(string):
958 ... value = int(string)
959 ... sqrt = math.sqrt(value)
960 ... if sqrt != int(sqrt):
961 ... msg = "%r is not a perfect square" % string
962 ... raise argparse.ArgumentTypeError(msg)
963 ... return value
964 ...
965 >>> parser = argparse.ArgumentParser(prog='PROG')
966 >>> parser.add_argument('foo', type=perfect_square)
967 >>> parser.parse_args('9'.split())
968 Namespace(foo=9)
969 >>> parser.parse_args('7'.split())
970 usage: PROG [-h] foo
971 PROG: error: argument foo: '7' is not a perfect square
972
Benjamin Peterson90c58022010-03-03 01:55:09 +0000973The choices_ keyword argument may be more convenient for type checkers that
974simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000975
976 >>> parser = argparse.ArgumentParser(prog='PROG')
977 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
978 >>> parser.parse_args('7'.split())
979 Namespace(foo=7)
980 >>> parser.parse_args('11'.split())
981 usage: PROG [-h] {5,6,7,8,9}
982 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
983
984See the choices_ section for more details.
985
986
987choices
988^^^^^^^
989
Éric Araujo67719bd2011-08-19 02:00:07 +0200990Some command-line arguments should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000991These can be handled by passing a container object as the ``choices`` keyword
Ezio Melottic69313a2011-04-22 01:29:13 +0300992argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Éric Araujo67719bd2011-08-19 02:00:07 +0200993parsed, argument values will be checked, and an error message will be displayed if
994the argument was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000995
996 >>> parser = argparse.ArgumentParser(prog='PROG')
997 >>> parser.add_argument('foo', choices='abc')
998 >>> parser.parse_args('c'.split())
999 Namespace(foo='c')
1000 >>> parser.parse_args('X'.split())
1001 usage: PROG [-h] {a,b,c}
1002 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
1003
1004Note that inclusion in the ``choices`` container is checked after any type_
1005conversions have been performed, so the type of the objects in the ``choices``
1006container should match the type_ specified::
1007
1008 >>> parser = argparse.ArgumentParser(prog='PROG')
1009 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
1010 >>> parser.parse_args('1j'.split())
1011 Namespace(foo=1j)
1012 >>> parser.parse_args('-- -4'.split())
1013 usage: PROG [-h] {1,1j}
1014 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
1015
1016Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +00001017value, so :class:`dict` objects, :class:`set` objects, custom containers,
1018etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001019
1020
1021required
1022^^^^^^^^
1023
Ezio Melotti01b600c2011-04-21 16:12:17 +03001024In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +03001025indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001026To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +03001027keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001028
1029 >>> parser = argparse.ArgumentParser()
1030 >>> parser.add_argument('--foo', required=True)
1031 >>> parser.parse_args(['--foo', 'BAR'])
1032 Namespace(foo='BAR')
1033 >>> parser.parse_args([])
1034 usage: argparse.py [-h] [--foo FOO]
1035 argparse.py: error: option --foo is required
1036
Ezio Melottic69313a2011-04-22 01:29:13 +03001037As the example shows, if an option is marked as ``required``,
1038:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1039present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001040
Benjamin Peterson90c58022010-03-03 01:55:09 +00001041.. note::
1042
1043 Required options are generally considered bad form because users expect
1044 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001045
1046
1047help
1048^^^^
1049
Benjamin Peterson90c58022010-03-03 01:55:09 +00001050The ``help`` value is a string containing a brief description of the argument.
1051When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001052command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001053argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001054
1055 >>> parser = argparse.ArgumentParser(prog='frobble')
1056 >>> parser.add_argument('--foo', action='store_true',
1057 ... help='foo the bars before frobbling')
1058 >>> parser.add_argument('bar', nargs='+',
1059 ... help='one of the bars to be frobbled')
1060 >>> parser.parse_args('-h'.split())
1061 usage: frobble [-h] [--foo] bar [bar ...]
1062
1063 positional arguments:
1064 bar one of the bars to be frobbled
1065
1066 optional arguments:
1067 -h, --help show this help message and exit
1068 --foo foo the bars before frobbling
1069
1070The ``help`` strings can include various format specifiers to avoid repetition
1071of things like the program name or the argument default_. The available
1072specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001073:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001074
1075 >>> parser = argparse.ArgumentParser(prog='frobble')
1076 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1077 ... help='the bar to %(prog)s (default: %(default)s)')
1078 >>> parser.print_help()
1079 usage: frobble [-h] [bar]
1080
1081 positional arguments:
1082 bar the bar to frobble (default: 42)
1083
1084 optional arguments:
1085 -h, --help show this help message and exit
1086
Sandro Tosi711f5472012-01-03 18:31:51 +01001087:mod:`argparse` supports silencing the help entry for certain options, by
1088setting the ``help`` value to ``argparse.SUPPRESS``::
1089
1090 >>> parser = argparse.ArgumentParser(prog='frobble')
1091 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1092 >>> parser.print_help()
1093 usage: frobble [-h]
1094
1095 optional arguments:
1096 -h, --help show this help message and exit
1097
Benjamin Petersona39e9662010-03-02 22:05:59 +00001098
1099metavar
1100^^^^^^^
1101
Benjamin Peterson90c58022010-03-03 01:55:09 +00001102When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001103to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001104value as the "name" of each object. By default, for positional argument
1105actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001106the dest_ value is uppercased. So, a single positional argument with
Eli Benderskybba1dd52011-11-11 16:42:11 +02001107``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujo67719bd2011-08-19 02:00:07 +02001108optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson90c58022010-03-03 01:55:09 +00001109will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001110
1111 >>> parser = argparse.ArgumentParser()
1112 >>> parser.add_argument('--foo')
1113 >>> parser.add_argument('bar')
1114 >>> parser.parse_args('X --foo Y'.split())
1115 Namespace(bar='X', foo='Y')
1116 >>> parser.print_help()
1117 usage: [-h] [--foo FOO] bar
1118
1119 positional arguments:
1120 bar
1121
1122 optional arguments:
1123 -h, --help show this help message and exit
1124 --foo FOO
1125
Benjamin Peterson90c58022010-03-03 01:55:09 +00001126An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001127
1128 >>> parser = argparse.ArgumentParser()
1129 >>> parser.add_argument('--foo', metavar='YYY')
1130 >>> parser.add_argument('bar', metavar='XXX')
1131 >>> parser.parse_args('X --foo Y'.split())
1132 Namespace(bar='X', foo='Y')
1133 >>> parser.print_help()
1134 usage: [-h] [--foo YYY] XXX
1135
1136 positional arguments:
1137 XXX
1138
1139 optional arguments:
1140 -h, --help show this help message and exit
1141 --foo YYY
1142
1143Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001144attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1145by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001146
1147Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001148Providing a tuple to ``metavar`` specifies a different display for each of the
1149arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001150
1151 >>> parser = argparse.ArgumentParser(prog='PROG')
1152 >>> parser.add_argument('-x', nargs=2)
1153 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1154 >>> parser.print_help()
1155 usage: PROG [-h] [-x X X] [--foo bar baz]
1156
1157 optional arguments:
1158 -h, --help show this help message and exit
1159 -x X X
1160 --foo bar baz
1161
1162
1163dest
1164^^^^
1165
Benjamin Peterson90c58022010-03-03 01:55:09 +00001166Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001167object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1168attribute is determined by the ``dest`` keyword argument of
1169:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1170``dest`` is normally supplied as the first argument to
1171:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001172
1173 >>> parser = argparse.ArgumentParser()
1174 >>> parser.add_argument('bar')
1175 >>> parser.parse_args('XXX'.split())
1176 Namespace(bar='XXX')
1177
1178For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001179the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo67719bd2011-08-19 02:00:07 +02001180taking the first long option string and stripping away the initial ``--``
Benjamin Petersona39e9662010-03-02 22:05:59 +00001181string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo67719bd2011-08-19 02:00:07 +02001182the first short option string by stripping the initial ``-`` character. Any
1183internal ``-`` characters will be converted to ``_`` characters to make sure
Georg Brandld2decd92010-03-02 22:17:38 +00001184the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001185behavior::
1186
1187 >>> parser = argparse.ArgumentParser()
1188 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1189 >>> parser.add_argument('-x', '-y')
1190 >>> parser.parse_args('-f 1 -x 2'.split())
1191 Namespace(foo_bar='1', x='2')
1192 >>> parser.parse_args('--foo 1 -y 2'.split())
1193 Namespace(foo_bar='1', x='2')
1194
Benjamin Peterson90c58022010-03-03 01:55:09 +00001195``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001196
1197 >>> parser = argparse.ArgumentParser()
1198 >>> parser.add_argument('--foo', dest='bar')
1199 >>> parser.parse_args('--foo XXX'.split())
1200 Namespace(bar='XXX')
1201
1202
1203The parse_args() method
1204-----------------------
1205
Georg Brandlb8d0e362010-11-26 07:53:50 +00001206.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001207
Benjamin Peterson90c58022010-03-03 01:55:09 +00001208 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001209 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001210
1211 Previous calls to :meth:`add_argument` determine exactly what objects are
1212 created and how they are assigned. See the documentation for
1213 :meth:`add_argument` for details.
1214
Éric Araujo67719bd2011-08-19 02:00:07 +02001215 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001216 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001217
Georg Brandlb8d0e362010-11-26 07:53:50 +00001218
Benjamin Petersona39e9662010-03-02 22:05:59 +00001219Option value syntax
1220^^^^^^^^^^^^^^^^^^^
1221
Ezio Melottic69313a2011-04-22 01:29:13 +03001222The :meth:`~ArgumentParser.parse_args` method supports several ways of
1223specifying the value of an option (if it takes one). In the simplest case, the
1224option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001225
1226 >>> parser = argparse.ArgumentParser(prog='PROG')
1227 >>> parser.add_argument('-x')
1228 >>> parser.add_argument('--foo')
1229 >>> parser.parse_args('-x X'.split())
1230 Namespace(foo=None, x='X')
1231 >>> parser.parse_args('--foo FOO'.split())
1232 Namespace(foo='FOO', x=None)
1233
Benjamin Peterson90c58022010-03-03 01:55:09 +00001234For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001235and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001236separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001237
1238 >>> parser.parse_args('--foo=FOO'.split())
1239 Namespace(foo='FOO', x=None)
1240
Benjamin Peterson90c58022010-03-03 01:55:09 +00001241For short options (options only one character long), the option and its value
1242can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001243
1244 >>> parser.parse_args('-xX'.split())
1245 Namespace(foo=None, x='X')
1246
Benjamin Peterson90c58022010-03-03 01:55:09 +00001247Several short options can be joined together, using only a single ``-`` prefix,
1248as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001249
1250 >>> parser = argparse.ArgumentParser(prog='PROG')
1251 >>> parser.add_argument('-x', action='store_true')
1252 >>> parser.add_argument('-y', action='store_true')
1253 >>> parser.add_argument('-z')
1254 >>> parser.parse_args('-xyzZ'.split())
1255 Namespace(x=True, y=True, z='Z')
1256
1257
1258Invalid arguments
1259^^^^^^^^^^^^^^^^^
1260
Ezio Melottic69313a2011-04-22 01:29:13 +03001261While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1262variety of errors, including ambiguous options, invalid types, invalid options,
1263wrong number of positional arguments, etc. When it encounters such an error,
1264it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001265
1266 >>> parser = argparse.ArgumentParser(prog='PROG')
1267 >>> parser.add_argument('--foo', type=int)
1268 >>> parser.add_argument('bar', nargs='?')
1269
1270 >>> # invalid type
1271 >>> parser.parse_args(['--foo', 'spam'])
1272 usage: PROG [-h] [--foo FOO] [bar]
1273 PROG: error: argument --foo: invalid int value: 'spam'
1274
1275 >>> # invalid option
1276 >>> parser.parse_args(['--bar'])
1277 usage: PROG [-h] [--foo FOO] [bar]
1278 PROG: error: no such option: --bar
1279
1280 >>> # wrong number of arguments
1281 >>> parser.parse_args(['spam', 'badger'])
1282 usage: PROG [-h] [--foo FOO] [bar]
1283 PROG: error: extra arguments found: badger
1284
1285
Éric Araujo67719bd2011-08-19 02:00:07 +02001286Arguments containing ``-``
1287^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001288
Ezio Melottic69313a2011-04-22 01:29:13 +03001289The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1290the user has clearly made a mistake, but some situations are inherently
Éric Araujo67719bd2011-08-19 02:00:07 +02001291ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melottic69313a2011-04-22 01:29:13 +03001292attempt to specify an option or an attempt to provide a positional argument.
1293The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo67719bd2011-08-19 02:00:07 +02001294arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melottic69313a2011-04-22 01:29:13 +03001295there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001296
1297 >>> parser = argparse.ArgumentParser(prog='PROG')
1298 >>> parser.add_argument('-x')
1299 >>> parser.add_argument('foo', nargs='?')
1300
1301 >>> # no negative number options, so -1 is a positional argument
1302 >>> parser.parse_args(['-x', '-1'])
1303 Namespace(foo=None, x='-1')
1304
1305 >>> # no negative number options, so -1 and -5 are positional arguments
1306 >>> parser.parse_args(['-x', '-1', '-5'])
1307 Namespace(foo='-5', x='-1')
1308
1309 >>> parser = argparse.ArgumentParser(prog='PROG')
1310 >>> parser.add_argument('-1', dest='one')
1311 >>> parser.add_argument('foo', nargs='?')
1312
1313 >>> # negative number options present, so -1 is an option
1314 >>> parser.parse_args(['-1', 'X'])
1315 Namespace(foo=None, one='X')
1316
1317 >>> # negative number options present, so -2 is an option
1318 >>> parser.parse_args(['-2'])
1319 usage: PROG [-h] [-1 ONE] [foo]
1320 PROG: error: no such option: -2
1321
1322 >>> # negative number options present, so both -1s are options
1323 >>> parser.parse_args(['-1', '-1'])
1324 usage: PROG [-h] [-1 ONE] [foo]
1325 PROG: error: argument -1: expected one argument
1326
Éric Araujo67719bd2011-08-19 02:00:07 +02001327If you have positional arguments that must begin with ``-`` and don't look
Benjamin Petersona39e9662010-03-02 22:05:59 +00001328like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001329:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1330argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001331
1332 >>> parser.parse_args(['--', '-f'])
1333 Namespace(foo='-f', one=None)
1334
1335
1336Argument abbreviations
1337^^^^^^^^^^^^^^^^^^^^^^
1338
Ezio Melottic69313a2011-04-22 01:29:13 +03001339The :meth:`~ArgumentParser.parse_args` method allows long options to be
1340abbreviated if the abbreviation is unambiguous::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001341
1342 >>> parser = argparse.ArgumentParser(prog='PROG')
1343 >>> parser.add_argument('-bacon')
1344 >>> parser.add_argument('-badger')
1345 >>> parser.parse_args('-bac MMM'.split())
1346 Namespace(bacon='MMM', badger=None)
1347 >>> parser.parse_args('-bad WOOD'.split())
1348 Namespace(bacon=None, badger='WOOD')
1349 >>> parser.parse_args('-ba BA'.split())
1350 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1351 PROG: error: ambiguous option: -ba could match -badger, -bacon
1352
Benjamin Peterson90c58022010-03-03 01:55:09 +00001353An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001354
1355
1356Beyond ``sys.argv``
1357^^^^^^^^^^^^^^^^^^^
1358
Éric Araujo67719bd2011-08-19 02:00:07 +02001359Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Georg Brandld2decd92010-03-02 22:17:38 +00001360of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001361:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1362interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001363
1364 >>> parser = argparse.ArgumentParser()
1365 >>> parser.add_argument(
1366 ... 'integers', metavar='int', type=int, choices=xrange(10),
1367 ... nargs='+', help='an integer in the range 0..9')
1368 >>> parser.add_argument(
1369 ... '--sum', dest='accumulate', action='store_const', const=sum,
1370 ... default=max, help='sum the integers (default: find the max)')
1371 >>> parser.parse_args(['1', '2', '3', '4'])
1372 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1373 >>> parser.parse_args('1 2 3 4 --sum'.split())
1374 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1375
1376
Steven Bethard3f69a052011-03-26 19:59:02 +01001377The Namespace object
1378^^^^^^^^^^^^^^^^^^^^
1379
Éric Araujof0d44bc2011-07-29 17:59:17 +02001380.. class:: Namespace
1381
1382 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1383 an object holding attributes and return it.
1384
1385This class is deliberately simple, just an :class:`object` subclass with a
1386readable string representation. If you prefer to have dict-like view of the
1387attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001388
1389 >>> parser = argparse.ArgumentParser()
1390 >>> parser.add_argument('--foo')
1391 >>> args = parser.parse_args(['--foo', 'BAR'])
1392 >>> vars(args)
1393 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001394
Benjamin Peterson90c58022010-03-03 01:55:09 +00001395It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001396already existing object, rather than a new :class:`Namespace` object. This can
1397be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001398
1399 >>> class C(object):
1400 ... pass
1401 ...
1402 >>> c = C()
1403 >>> parser = argparse.ArgumentParser()
1404 >>> parser.add_argument('--foo')
1405 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1406 >>> c.foo
1407 'BAR'
1408
1409
1410Other utilities
1411---------------
1412
1413Sub-commands
1414^^^^^^^^^^^^
1415
Benjamin Peterson90c58022010-03-03 01:55:09 +00001416.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001417
Benjamin Peterson90c58022010-03-03 01:55:09 +00001418 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001419 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001420 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001421 this way can be a particularly good idea when a program performs several
1422 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001423 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001424 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1425 called with no arguments and returns an special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001426 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1427 command name and any :class:`ArgumentParser` constructor arguments, and
1428 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001429
1430 Some example usage::
1431
1432 >>> # create the top-level parser
1433 >>> parser = argparse.ArgumentParser(prog='PROG')
1434 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1435 >>> subparsers = parser.add_subparsers(help='sub-command help')
1436 >>>
1437 >>> # create the parser for the "a" command
1438 >>> parser_a = subparsers.add_parser('a', help='a help')
1439 >>> parser_a.add_argument('bar', type=int, help='bar help')
1440 >>>
1441 >>> # create the parser for the "b" command
1442 >>> parser_b = subparsers.add_parser('b', help='b help')
1443 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1444 >>>
Éric Araujo67719bd2011-08-19 02:00:07 +02001445 >>> # parse some argument lists
Benjamin Petersona39e9662010-03-02 22:05:59 +00001446 >>> parser.parse_args(['a', '12'])
1447 Namespace(bar=12, foo=False)
1448 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1449 Namespace(baz='Z', foo=True)
1450
1451 Note that the object returned by :meth:`parse_args` will only contain
1452 attributes for the main parser and the subparser that was selected by the
1453 command line (and not any other subparsers). So in the example above, when
Éric Araujo67719bd2011-08-19 02:00:07 +02001454 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1455 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001456 ``baz`` attributes are present.
1457
1458 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001459 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001460 include parent parser or sibling parser messages. (A help message for each
1461 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001462 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001463
1464 ::
1465
1466 >>> parser.parse_args(['--help'])
1467 usage: PROG [-h] [--foo] {a,b} ...
1468
1469 positional arguments:
1470 {a,b} sub-command help
1471 a a help
1472 b b help
1473
1474 optional arguments:
1475 -h, --help show this help message and exit
1476 --foo foo help
1477
1478 >>> parser.parse_args(['a', '--help'])
1479 usage: PROG a [-h] bar
1480
1481 positional arguments:
1482 bar bar help
1483
1484 optional arguments:
1485 -h, --help show this help message and exit
1486
1487 >>> parser.parse_args(['b', '--help'])
1488 usage: PROG b [-h] [--baz {X,Y,Z}]
1489
1490 optional arguments:
1491 -h, --help show this help message and exit
1492 --baz {X,Y,Z} baz help
1493
Georg Brandld2decd92010-03-02 22:17:38 +00001494 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1495 keyword arguments. When either is present, the subparser's commands will
1496 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001497
1498 >>> parser = argparse.ArgumentParser()
1499 >>> subparsers = parser.add_subparsers(title='subcommands',
1500 ... description='valid subcommands',
1501 ... help='additional help')
1502 >>> subparsers.add_parser('foo')
1503 >>> subparsers.add_parser('bar')
1504 >>> parser.parse_args(['-h'])
1505 usage: [-h] {foo,bar} ...
1506
1507 optional arguments:
1508 -h, --help show this help message and exit
1509
1510 subcommands:
1511 valid subcommands
1512
1513 {foo,bar} additional help
1514
1515
Georg Brandld2decd92010-03-02 22:17:38 +00001516 One particularly effective way of handling sub-commands is to combine the use
1517 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1518 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001519 example::
1520
1521 >>> # sub-command functions
1522 >>> def foo(args):
1523 ... print args.x * args.y
1524 ...
1525 >>> def bar(args):
1526 ... print '((%s))' % args.z
1527 ...
1528 >>> # create the top-level parser
1529 >>> parser = argparse.ArgumentParser()
1530 >>> subparsers = parser.add_subparsers()
1531 >>>
1532 >>> # create the parser for the "foo" command
1533 >>> parser_foo = subparsers.add_parser('foo')
1534 >>> parser_foo.add_argument('-x', type=int, default=1)
1535 >>> parser_foo.add_argument('y', type=float)
1536 >>> parser_foo.set_defaults(func=foo)
1537 >>>
1538 >>> # create the parser for the "bar" command
1539 >>> parser_bar = subparsers.add_parser('bar')
1540 >>> parser_bar.add_argument('z')
1541 >>> parser_bar.set_defaults(func=bar)
1542 >>>
1543 >>> # parse the args and call whatever function was selected
1544 >>> args = parser.parse_args('foo 1 -x 2'.split())
1545 >>> args.func(args)
1546 2.0
1547 >>>
1548 >>> # parse the args and call whatever function was selected
1549 >>> args = parser.parse_args('bar XYZYX'.split())
1550 >>> args.func(args)
1551 ((XYZYX))
1552
Éric Araujobb42f5e2012-02-20 02:08:01 +01001553 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson90c58022010-03-03 01:55:09 +00001554 appropriate function after argument parsing is complete. Associating
1555 functions with actions like this is typically the easiest way to handle the
1556 different actions for each of your subparsers. However, if it is necessary
1557 to check the name of the subparser that was invoked, the ``dest`` keyword
1558 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001559
1560 >>> parser = argparse.ArgumentParser()
1561 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1562 >>> subparser1 = subparsers.add_parser('1')
1563 >>> subparser1.add_argument('-x')
1564 >>> subparser2 = subparsers.add_parser('2')
1565 >>> subparser2.add_argument('y')
1566 >>> parser.parse_args(['2', 'frobble'])
1567 Namespace(subparser_name='2', y='frobble')
1568
1569
1570FileType objects
1571^^^^^^^^^^^^^^^^
1572
1573.. class:: FileType(mode='r', bufsize=None)
1574
1575 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001576 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujo67719bd2011-08-19 02:00:07 +02001577 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujobb42f5e2012-02-20 02:08:01 +01001578 with the requested modes and buffer sizes::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001579
Éric Araujobb42f5e2012-02-20 02:08:01 +01001580 >>> parser = argparse.ArgumentParser()
1581 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1582 >>> parser.parse_args(['--output', 'out'])
1583 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001584
1585 FileType objects understand the pseudo-argument ``'-'`` and automatically
1586 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujobb42f5e2012-02-20 02:08:01 +01001587 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001588
Éric Araujobb42f5e2012-02-20 02:08:01 +01001589 >>> parser = argparse.ArgumentParser()
1590 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1591 >>> parser.parse_args(['-'])
1592 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001593
1594
1595Argument groups
1596^^^^^^^^^^^^^^^
1597
Georg Brandlb8d0e362010-11-26 07:53:50 +00001598.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001599
Benjamin Peterson90c58022010-03-03 01:55:09 +00001600 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001601 "positional arguments" and "optional arguments" when displaying help
1602 messages. When there is a better conceptual grouping of arguments than this
1603 default one, appropriate groups can be created using the
1604 :meth:`add_argument_group` method::
1605
1606 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1607 >>> group = parser.add_argument_group('group')
1608 >>> group.add_argument('--foo', help='foo help')
1609 >>> group.add_argument('bar', help='bar help')
1610 >>> parser.print_help()
1611 usage: PROG [--foo FOO] bar
1612
1613 group:
1614 bar bar help
1615 --foo FOO foo help
1616
1617 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001618 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1619 :class:`ArgumentParser`. When an argument is added to the group, the parser
1620 treats it just like a normal argument, but displays the argument in a
1621 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001622 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001623 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001624
1625 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1626 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1627 >>> group1.add_argument('foo', help='foo help')
1628 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1629 >>> group2.add_argument('--bar', help='bar help')
1630 >>> parser.print_help()
1631 usage: PROG [--bar BAR] foo
1632
1633 group1:
1634 group1 description
1635
1636 foo foo help
1637
1638 group2:
1639 group2 description
1640
1641 --bar BAR bar help
1642
Sandro Tosi48a88952012-03-26 19:35:52 +02001643 Note that any arguments not in your user-defined groups will end up back
1644 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001645
1646
1647Mutual exclusion
1648^^^^^^^^^^^^^^^^
1649
Georg Brandlb8d0e362010-11-26 07:53:50 +00001650.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001651
Ezio Melotti01b600c2011-04-21 16:12:17 +03001652 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1653 one of the arguments in the mutually exclusive group was present on the
1654 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001655
1656 >>> parser = argparse.ArgumentParser(prog='PROG')
1657 >>> group = parser.add_mutually_exclusive_group()
1658 >>> group.add_argument('--foo', action='store_true')
1659 >>> group.add_argument('--bar', action='store_false')
1660 >>> parser.parse_args(['--foo'])
1661 Namespace(bar=True, foo=True)
1662 >>> parser.parse_args(['--bar'])
1663 Namespace(bar=False, foo=False)
1664 >>> parser.parse_args(['--foo', '--bar'])
1665 usage: PROG [-h] [--foo | --bar]
1666 PROG: error: argument --bar: not allowed with argument --foo
1667
Georg Brandlb8d0e362010-11-26 07:53:50 +00001668 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001669 argument, to indicate that at least one of the mutually exclusive arguments
1670 is required::
1671
1672 >>> parser = argparse.ArgumentParser(prog='PROG')
1673 >>> group = parser.add_mutually_exclusive_group(required=True)
1674 >>> group.add_argument('--foo', action='store_true')
1675 >>> group.add_argument('--bar', action='store_false')
1676 >>> parser.parse_args([])
1677 usage: PROG [-h] (--foo | --bar)
1678 PROG: error: one of the arguments --foo --bar is required
1679
1680 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001681 *title* and *description* arguments of
1682 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001683
1684
1685Parser defaults
1686^^^^^^^^^^^^^^^
1687
Benjamin Peterson90c58022010-03-03 01:55:09 +00001688.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001689
Georg Brandld2decd92010-03-02 22:17:38 +00001690 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujo67719bd2011-08-19 02:00:07 +02001691 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001692 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001693 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001694 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001695
1696 >>> parser = argparse.ArgumentParser()
1697 >>> parser.add_argument('foo', type=int)
1698 >>> parser.set_defaults(bar=42, baz='badger')
1699 >>> parser.parse_args(['736'])
1700 Namespace(bar=42, baz='badger', foo=736)
1701
Benjamin Peterson90c58022010-03-03 01:55:09 +00001702 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001703
1704 >>> parser = argparse.ArgumentParser()
1705 >>> parser.add_argument('--foo', default='bar')
1706 >>> parser.set_defaults(foo='spam')
1707 >>> parser.parse_args([])
1708 Namespace(foo='spam')
1709
Benjamin Peterson90c58022010-03-03 01:55:09 +00001710 Parser-level defaults can be particularly useful when working with multiple
1711 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1712 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001713
Benjamin Peterson90c58022010-03-03 01:55:09 +00001714.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001715
1716 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001717 :meth:`~ArgumentParser.add_argument` or by
1718 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001719
1720 >>> parser = argparse.ArgumentParser()
1721 >>> parser.add_argument('--foo', default='badger')
1722 >>> parser.get_default('foo')
1723 'badger'
1724
1725
1726Printing help
1727^^^^^^^^^^^^^
1728
Ezio Melottic69313a2011-04-22 01:29:13 +03001729In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1730care of formatting and printing any usage or error messages. However, several
1731formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001732
Georg Brandlb8d0e362010-11-26 07:53:50 +00001733.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001734
1735 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001736 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001737 assumed.
1738
Georg Brandlb8d0e362010-11-26 07:53:50 +00001739.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001740
1741 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001742 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001743 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001744
1745There are also variants of these methods that simply return a string instead of
1746printing it:
1747
Georg Brandlb8d0e362010-11-26 07:53:50 +00001748.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001749
1750 Return a string containing a brief description of how the
1751 :class:`ArgumentParser` should be invoked on the command line.
1752
Georg Brandlb8d0e362010-11-26 07:53:50 +00001753.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001754
1755 Return a string containing a help message, including the program usage and
1756 information about the arguments registered with the :class:`ArgumentParser`.
1757
1758
Benjamin Petersona39e9662010-03-02 22:05:59 +00001759Partial parsing
1760^^^^^^^^^^^^^^^
1761
Georg Brandlb8d0e362010-11-26 07:53:50 +00001762.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001763
Ezio Melotti12125822011-04-16 23:04:51 +03001764Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001765the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001766:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001767:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1768extra arguments are present. Instead, it returns a two item tuple containing
1769the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001770
1771::
1772
1773 >>> parser = argparse.ArgumentParser()
1774 >>> parser.add_argument('--foo', action='store_true')
1775 >>> parser.add_argument('bar')
1776 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1777 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1778
1779
1780Customizing file parsing
1781^^^^^^^^^^^^^^^^^^^^^^^^
1782
Benjamin Peterson90c58022010-03-03 01:55:09 +00001783.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001784
Georg Brandlb8d0e362010-11-26 07:53:50 +00001785 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001786 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001787 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1788 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001789
Georg Brandlb8d0e362010-11-26 07:53:50 +00001790 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001791 the argument file. It returns a list of arguments parsed from this string.
1792 The method is called once per line read from the argument file, in order.
1793
Georg Brandld2decd92010-03-02 22:17:38 +00001794 A useful override of this method is one that treats each space-separated word
1795 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001796
1797 def convert_arg_line_to_args(self, arg_line):
1798 for arg in arg_line.split():
1799 if not arg.strip():
1800 continue
1801 yield arg
1802
1803
Georg Brandlb8d0e362010-11-26 07:53:50 +00001804Exiting methods
1805^^^^^^^^^^^^^^^
1806
1807.. method:: ArgumentParser.exit(status=0, message=None)
1808
1809 This method terminates the program, exiting with the specified *status*
1810 and, if given, it prints a *message* before that.
1811
1812.. method:: ArgumentParser.error(message)
1813
1814 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001815 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001816
1817
Georg Brandl58df6792010-07-03 10:25:47 +00001818.. _argparse-from-optparse:
1819
Benjamin Petersona39e9662010-03-02 22:05:59 +00001820Upgrading optparse code
1821-----------------------
1822
Ezio Melottic69313a2011-04-22 01:29:13 +03001823Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001824with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1825transparently, particularly with the changes required to support the new
1826``nargs=`` specifiers and better usage messages. When most everything in
1827:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1828longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001829
Ezio Melotti01b600c2011-04-21 16:12:17 +03001830A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001831
Ezio Melottic69313a2011-04-22 01:29:13 +03001832* Replace all :meth:`optparse.OptionParser.add_option` calls with
1833 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001834
R David Murray5080cad2012-03-30 18:09:07 -04001835* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001836 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5080cad2012-03-30 18:09:07 -04001837 calls for the positional arguments. Keep in mind that what was previously
1838 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001839
1840* Replace callback actions and the ``callback_*`` keyword arguments with
1841 ``type`` or ``action`` arguments.
1842
1843* Replace string names for ``type`` keyword arguments with the corresponding
1844 type objects (e.g. int, float, complex, etc).
1845
Benjamin Peterson90c58022010-03-03 01:55:09 +00001846* Replace :class:`optparse.Values` with :class:`Namespace` and
1847 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1848 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001849
Georg Brandld2decd92010-03-02 22:17:38 +00001850* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001851 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001852 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001853
1854* Replace the OptionParser constructor ``version`` argument with a call to
1855 ``parser.add_argument('--version', action='version', version='<the version>')``