blob: edd1b903e7370f3bbfa0a8e4f8b4485c0b0509c1 [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 Melotti12125822011-04-16 23:04:51 +030015The :mod:`argparse` module makes it easy to write user-friendly command-line
Benjamin Peterson90c58022010-03-03 01:55:09 +000016interfaces. The program defines what arguments it requires, and :mod:`argparse`
Georg Brandld2decd92010-03-02 22:17:38 +000017will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson90c58022010-03-03 01:55:09 +000018module also automatically generates help and usage messages and issues errors
19when users give the program invalid arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +000020
Georg Brandlb8d0e362010-11-26 07:53:50 +000021
Benjamin Petersona39e9662010-03-02 22:05:59 +000022Example
23-------
24
Benjamin Peterson90c58022010-03-03 01:55:09 +000025The following code is a Python program that takes a list of integers and
26produces either the sum or the max::
Benjamin Petersona39e9662010-03-02 22:05:59 +000027
28 import argparse
29
30 parser = argparse.ArgumentParser(description='Process some integers.')
31 parser.add_argument('integers', metavar='N', type=int, nargs='+',
32 help='an integer for the accumulator')
33 parser.add_argument('--sum', dest='accumulate', action='store_const',
34 const=sum, default=max,
35 help='sum the integers (default: find the max)')
36
37 args = parser.parse_args()
38 print args.accumulate(args.integers)
39
40Assuming the Python code above is saved into a file called ``prog.py``, it can
41be run at the command line and provides useful help messages::
42
43 $ prog.py -h
44 usage: prog.py [-h] [--sum] N [N ...]
45
46 Process some integers.
47
48 positional arguments:
49 N an integer for the accumulator
50
51 optional arguments:
52 -h, --help show this help message and exit
53 --sum sum the integers (default: find the max)
54
55When run with the appropriate arguments, it prints either the sum or the max of
56the command-line integers::
57
58 $ prog.py 1 2 3 4
59 4
60
61 $ prog.py 1 2 3 4 --sum
62 10
63
64If invalid arguments are passed in, it will issue an error::
65
66 $ prog.py a b c
67 usage: prog.py [-h] [--sum] N [N ...]
68 prog.py: error: argument N: invalid int value: 'a'
69
70The following sections walk you through this example.
71
Georg Brandlb8d0e362010-11-26 07:53:50 +000072
Benjamin Petersona39e9662010-03-02 22:05:59 +000073Creating a parser
74^^^^^^^^^^^^^^^^^
75
Benjamin Petersonac80c152010-03-03 21:28:25 +000076The first step in using the :mod:`argparse` is creating an
Benjamin Peterson90c58022010-03-03 01:55:09 +000077:class:`ArgumentParser` object::
Benjamin Petersona39e9662010-03-02 22:05:59 +000078
79 >>> parser = argparse.ArgumentParser(description='Process some integers.')
80
81The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotti2eab88e2011-04-21 15:26:46 +030082parse the command line into Python data types.
Benjamin Petersona39e9662010-03-02 22:05:59 +000083
84
85Adding arguments
86^^^^^^^^^^^^^^^^
87
Benjamin Peterson90c58022010-03-03 01:55:09 +000088Filling an :class:`ArgumentParser` with information about program arguments is
89done by making calls to the :meth:`~ArgumentParser.add_argument` method.
90Generally, these calls tell the :class:`ArgumentParser` how to take the strings
91on the command line and turn them into objects. This information is stored and
92used when :meth:`~ArgumentParser.parse_args` is called. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +000093
94 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
95 ... help='an integer for the accumulator')
96 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
97 ... const=sum, default=max,
98 ... help='sum the integers (default: find the max)')
99
Ezio Melottic69313a2011-04-22 01:29:13 +0300100Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Georg Brandld2decd92010-03-02 22:17:38 +0000101two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
102will be a list of one or more ints, and the ``accumulate`` attribute will be
103either the :func:`sum` function, if ``--sum`` was specified at the command line,
104or the :func:`max` function if it was not.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000105
Georg Brandlb8d0e362010-11-26 07:53:50 +0000106
Benjamin Petersona39e9662010-03-02 22:05:59 +0000107Parsing arguments
108^^^^^^^^^^^^^^^^^
109
Éric Araujo67719bd2011-08-19 02:00:07 +0200110:class:`ArgumentParser` parses arguments through the
Ezio Melotti12125822011-04-16 23:04:51 +0300111:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujo67719bd2011-08-19 02:00:07 +0200112convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujof0d44bc2011-07-29 17:59:17 +0200113In most cases, this means a simple :class:`Namespace` object will be built up from
Ezio Melotti12125822011-04-16 23:04:51 +0300114attributes parsed out of the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000115
116 >>> parser.parse_args(['--sum', '7', '-1', '42'])
117 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
118
Benjamin Peterson90c58022010-03-03 01:55:09 +0000119In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
120arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujo67719bd2011-08-19 02:00:07 +0200121command-line arguments from :data:`sys.argv`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000122
123
124ArgumentParser objects
125----------------------
126
Ezio Melotti569083a2011-04-21 23:30:27 +0300127.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000128
Georg Brandld2decd92010-03-02 22:17:38 +0000129 Create a new :class:`ArgumentParser` object. Each parameter has its own more
Benjamin Petersona39e9662010-03-02 22:05:59 +0000130 detailed description below, but in short they are:
131
132 * description_ - Text to display before the argument help.
133
134 * epilog_ - Text to display after the argument help.
135
Benjamin Peterson90c58022010-03-03 01:55:09 +0000136 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000137
138 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000139 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000140
Benjamin Peterson90c58022010-03-03 01:55:09 +0000141 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Petersona39e9662010-03-02 22:05:59 +0000142 also be included.
143
144 * prefix_chars_ - The set of characters that prefix optional arguments.
145 (default: '-')
146
147 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson90c58022010-03-03 01:55:09 +0000148 which additional arguments should be read. (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000149
150 * formatter_class_ - A class for customizing the help output.
151
152 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
153 conflicting optionals.
154
Benjamin Peterson90c58022010-03-03 01:55:09 +0000155 * prog_ - The name of the program (default:
Éric Araujo7ce05e02011-09-01 19:54:05 +0200156 ``sys.argv[0]``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000157
Benjamin Peterson90c58022010-03-03 01:55:09 +0000158 * usage_ - The string describing the program usage (default: generated)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000159
Benjamin Peterson90c58022010-03-03 01:55:09 +0000160The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000161
162
163description
164^^^^^^^^^^^
165
Benjamin Peterson90c58022010-03-03 01:55:09 +0000166Most calls to the :class:`ArgumentParser` constructor will use the
167``description=`` keyword argument. This argument gives a brief description of
168what the program does and how it works. In help messages, the description is
169displayed between the command-line usage string and the help messages for the
170various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000171
172 >>> parser = argparse.ArgumentParser(description='A foo that bars')
173 >>> parser.print_help()
174 usage: argparse.py [-h]
175
176 A foo that bars
177
178 optional arguments:
179 -h, --help show this help message and exit
180
181By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000182given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000183
184
185epilog
186^^^^^^
187
188Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000189description of the arguments. Such text can be specified using the ``epilog=``
190argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000191
192 >>> parser = argparse.ArgumentParser(
193 ... description='A foo that bars',
194 ... epilog="And that's how you'd foo a bar")
195 >>> parser.print_help()
196 usage: argparse.py [-h]
197
198 A foo that bars
199
200 optional arguments:
201 -h, --help show this help message and exit
202
203 And that's how you'd foo a bar
204
205As with the description_ argument, the ``epilog=`` text is by default
206line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000207argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000208
209
210add_help
211^^^^^^^^
212
R. David Murray1cbf78e2010-08-03 18:14:01 +0000213By default, ArgumentParser objects add an option which simply displays
214the parser's help message. For example, consider a file named
Benjamin Petersona39e9662010-03-02 22:05:59 +0000215``myprogram.py`` containing the following code::
216
217 import argparse
218 parser = argparse.ArgumentParser()
219 parser.add_argument('--foo', help='foo help')
220 args = parser.parse_args()
221
Ezio Melotti12125822011-04-16 23:04:51 +0300222If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Petersona39e9662010-03-02 22:05:59 +0000223help will be printed::
224
225 $ python myprogram.py --help
226 usage: myprogram.py [-h] [--foo FOO]
227
228 optional arguments:
229 -h, --help show this help message and exit
230 --foo FOO foo help
231
232Occasionally, it may be useful to disable the addition of this help option.
233This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson90c58022010-03-03 01:55:09 +0000234:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000235
236 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
237 >>> parser.add_argument('--foo', help='foo help')
238 >>> parser.print_help()
239 usage: PROG [--foo FOO]
240
241 optional arguments:
242 --foo FOO foo help
243
R. David Murray1cbf78e2010-08-03 18:14:01 +0000244The help option is typically ``-h/--help``. The exception to this is
Éric Araujo67719bd2011-08-19 02:00:07 +0200245if the ``prefix_chars=`` is specified and does not include ``-``, in
R. David Murray1cbf78e2010-08-03 18:14:01 +0000246which case ``-h`` and ``--help`` are not valid options. In
247this case, the first character in ``prefix_chars`` is used to prefix
248the help options::
249
250 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
251 >>> parser.print_help()
252 usage: PROG [+h]
253
254 optional arguments:
255 +h, ++help show this help message and exit
256
257
Benjamin Petersona39e9662010-03-02 22:05:59 +0000258prefix_chars
259^^^^^^^^^^^^
260
Éric Araujo67719bd2011-08-19 02:00:07 +0200261Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
R. David Murray1cbf78e2010-08-03 18:14:01 +0000262Parsers that need to support different or additional prefix
263characters, e.g. for options
Benjamin Petersona39e9662010-03-02 22:05:59 +0000264like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
265to the ArgumentParser constructor::
266
267 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
268 >>> parser.add_argument('+f')
269 >>> parser.add_argument('++bar')
270 >>> parser.parse_args('+f X ++bar Y'.split())
271 Namespace(bar='Y', f='X')
272
273The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
Éric Araujo67719bd2011-08-19 02:00:07 +0200274characters that does not include ``-`` will cause ``-f/--foo`` options to be
Benjamin Petersona39e9662010-03-02 22:05:59 +0000275disallowed.
276
277
278fromfile_prefix_chars
279^^^^^^^^^^^^^^^^^^^^^
280
Benjamin Peterson90c58022010-03-03 01:55:09 +0000281Sometimes, for example when dealing with a particularly long argument lists, it
282may make sense to keep the list of arguments in a file rather than typing it out
283at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
284:class:`ArgumentParser` constructor, then arguments that start with any of the
285specified characters will be treated as files, and will be replaced by the
286arguments they contain. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000287
Benjamin Peterson90c58022010-03-03 01:55:09 +0000288 >>> with open('args.txt', 'w') as fp:
289 ... fp.write('-f\nbar')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000290 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
291 >>> parser.add_argument('-f')
292 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
293 Namespace(f='bar')
294
295Arguments read from a file must by default be one per line (but see also
Ezio Melottic69313a2011-04-22 01:29:13 +0300296:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
297were in the same place as the original file referencing argument on the command
298line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
299is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000300
301The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
302arguments will never be treated as file references.
303
Georg Brandlb8d0e362010-11-26 07:53:50 +0000304
Benjamin Petersona39e9662010-03-02 22:05:59 +0000305argument_default
306^^^^^^^^^^^^^^^^
307
308Generally, argument defaults are specified either by passing a default to
Ezio Melottic69313a2011-04-22 01:29:13 +0300309:meth:`~ArgumentParser.add_argument` or by calling the
310:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
311pairs. Sometimes however, it may be useful to specify a single parser-wide
312default for arguments. This can be accomplished by passing the
313``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
314to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson90c58022010-03-03 01:55:09 +0000315calls, we supply ``argument_default=SUPPRESS``::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000316
317 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
318 >>> parser.add_argument('--foo')
319 >>> parser.add_argument('bar', nargs='?')
320 >>> parser.parse_args(['--foo', '1', 'BAR'])
321 Namespace(bar='BAR', foo='1')
322 >>> parser.parse_args([])
323 Namespace()
324
325
326parents
327^^^^^^^
328
329Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000330repeating the definitions of these arguments, a single parser with all the
331shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
332can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
333objects, collects all the positional and optional actions from them, and adds
334these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000335
336 >>> parent_parser = argparse.ArgumentParser(add_help=False)
337 >>> parent_parser.add_argument('--parent', type=int)
338
339 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
340 >>> foo_parser.add_argument('foo')
341 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
342 Namespace(foo='XXX', parent=2)
343
344 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
345 >>> bar_parser.add_argument('--bar')
346 >>> bar_parser.parse_args(['--bar', 'YYY'])
347 Namespace(bar='YYY', parent=None)
348
Georg Brandld2decd92010-03-02 22:17:38 +0000349Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000350:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
351and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000352
Steven Bethard5e0062d2011-03-26 21:50:38 +0100353.. note::
354 You must fully initialize the parsers before passing them via ``parents=``.
355 If you change the parent parsers after the child parser, those changes will
356 not be reflected in the child.
357
Benjamin Petersona39e9662010-03-02 22:05:59 +0000358
359formatter_class
360^^^^^^^^^^^^^^^
361
Benjamin Peterson90c58022010-03-03 01:55:09 +0000362:class:`ArgumentParser` objects allow the help formatting to be customized by
363specifying an alternate formatting class. Currently, there are three such
Ezio Melottic69313a2011-04-22 01:29:13 +0300364classes:
365
366.. class:: RawDescriptionHelpFormatter
367 RawTextHelpFormatter
368 ArgumentDefaultsHelpFormatter
369
370The first two allow more control over how textual descriptions are displayed,
371while the last automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000372
Benjamin Peterson90c58022010-03-03 01:55:09 +0000373By default, :class:`ArgumentParser` objects line-wrap the description_ and
374epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000375
376 >>> parser = argparse.ArgumentParser(
377 ... prog='PROG',
378 ... description='''this description
379 ... was indented weird
380 ... but that is okay''',
381 ... epilog='''
382 ... likewise for this epilog whose whitespace will
383 ... be cleaned up and whose words will be wrapped
384 ... across a couple lines''')
385 >>> parser.print_help()
386 usage: PROG [-h]
387
388 this description was indented weird but that is okay
389
390 optional arguments:
391 -h, --help show this help message and exit
392
393 likewise for this epilog whose whitespace will be cleaned up and whose words
394 will be wrapped across a couple lines
395
Éric Araujo67719bd2011-08-19 02:00:07 +0200396Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000397indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000398should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000399
400 >>> parser = argparse.ArgumentParser(
401 ... prog='PROG',
402 ... formatter_class=argparse.RawDescriptionHelpFormatter,
403 ... description=textwrap.dedent('''\
404 ... Please do not mess up this text!
405 ... --------------------------------
406 ... I have indented it
407 ... exactly the way
408 ... I want it
409 ... '''))
410 >>> parser.print_help()
411 usage: PROG [-h]
412
413 Please do not mess up this text!
414 --------------------------------
415 I have indented it
416 exactly the way
417 I want it
418
419 optional arguments:
420 -h, --help show this help message and exit
421
Éric Araujo67719bd2011-08-19 02:00:07 +0200422:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson90c58022010-03-03 01:55:09 +0000423including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000424
Benjamin Peterson90c58022010-03-03 01:55:09 +0000425The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000426will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000427
428 >>> parser = argparse.ArgumentParser(
429 ... prog='PROG',
430 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
431 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
432 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
433 >>> parser.print_help()
434 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
435
436 positional arguments:
437 bar BAR! (default: [1, 2, 3])
438
439 optional arguments:
440 -h, --help show this help message and exit
441 --foo FOO FOO! (default: 42)
442
443
444conflict_handler
445^^^^^^^^^^^^^^^^
446
Benjamin Peterson90c58022010-03-03 01:55:09 +0000447:class:`ArgumentParser` objects do not allow two actions with the same option
448string. By default, :class:`ArgumentParser` objects raises an exception if an
449attempt is made to create an argument with an option string that is already in
450use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000451
452 >>> parser = argparse.ArgumentParser(prog='PROG')
453 >>> parser.add_argument('-f', '--foo', help='old foo help')
454 >>> parser.add_argument('--foo', help='new foo help')
455 Traceback (most recent call last):
456 ..
457 ArgumentError: argument --foo: conflicting option string(s): --foo
458
459Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000460older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000461``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000462:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000463
464 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
465 >>> parser.add_argument('-f', '--foo', help='old foo help')
466 >>> parser.add_argument('--foo', help='new foo help')
467 >>> parser.print_help()
468 usage: PROG [-h] [-f FOO] [--foo FOO]
469
470 optional arguments:
471 -h, --help show this help message and exit
472 -f FOO old foo help
473 --foo FOO new foo help
474
Benjamin Peterson90c58022010-03-03 01:55:09 +0000475Note that :class:`ArgumentParser` objects only remove an action if all of its
476option strings are overridden. So, in the example above, the old ``-f/--foo``
477action is retained as the ``-f`` action, because only the ``--foo`` option
478string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000479
480
481prog
482^^^^
483
Benjamin Peterson90c58022010-03-03 01:55:09 +0000484By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
485how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000486always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000487invoked on the command line. For example, consider a file named
488``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000489
490 import argparse
491 parser = argparse.ArgumentParser()
492 parser.add_argument('--foo', help='foo help')
493 args = parser.parse_args()
494
495The help for this program will display ``myprogram.py`` as the program name
496(regardless of where the program was invoked from)::
497
498 $ python myprogram.py --help
499 usage: myprogram.py [-h] [--foo FOO]
500
501 optional arguments:
502 -h, --help show this help message and exit
503 --foo FOO foo help
504 $ cd ..
505 $ python subdir\myprogram.py --help
506 usage: myprogram.py [-h] [--foo FOO]
507
508 optional arguments:
509 -h, --help show this help message and exit
510 --foo FOO foo help
511
512To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000513``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000514
515 >>> parser = argparse.ArgumentParser(prog='myprogram')
516 >>> parser.print_help()
517 usage: myprogram [-h]
518
519 optional arguments:
520 -h, --help show this help message and exit
521
522Note that the program name, whether determined from ``sys.argv[0]`` or from the
523``prog=`` argument, is available to help messages using the ``%(prog)s`` format
524specifier.
525
526::
527
528 >>> parser = argparse.ArgumentParser(prog='myprogram')
529 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
530 >>> parser.print_help()
531 usage: myprogram [-h] [--foo FOO]
532
533 optional arguments:
534 -h, --help show this help message and exit
535 --foo FOO foo of the myprogram program
536
537
538usage
539^^^^^
540
Benjamin Peterson90c58022010-03-03 01:55:09 +0000541By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000542arguments it contains::
543
544 >>> parser = argparse.ArgumentParser(prog='PROG')
545 >>> parser.add_argument('--foo', nargs='?', help='foo help')
546 >>> parser.add_argument('bar', nargs='+', help='bar help')
547 >>> parser.print_help()
548 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
549
550 positional arguments:
551 bar bar help
552
553 optional arguments:
554 -h, --help show this help message and exit
555 --foo [FOO] foo help
556
Benjamin Peterson90c58022010-03-03 01:55:09 +0000557The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000558
559 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
560 >>> parser.add_argument('--foo', nargs='?', help='foo help')
561 >>> parser.add_argument('bar', nargs='+', help='bar help')
562 >>> parser.print_help()
563 usage: PROG [options]
564
565 positional arguments:
566 bar bar help
567
568 optional arguments:
569 -h, --help show this help message and exit
570 --foo [FOO] foo help
571
Benjamin Peterson90c58022010-03-03 01:55:09 +0000572The ``%(prog)s`` format specifier is available to fill in the program name in
573your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000574
575
576The add_argument() method
577-------------------------
578
Ezio Melotti569083a2011-04-21 23:30:27 +0300579.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000580
Ezio Melotti12125822011-04-16 23:04:51 +0300581 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000582 has its own more detailed description below, but in short they are:
583
584 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300585 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000586
587 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300588 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000589
590 * nargs_ - The number of command-line arguments that should be consumed.
591
592 * const_ - A constant value required by some action_ and nargs_ selections.
593
594 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300595 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000596
Ezio Melotti12125822011-04-16 23:04:51 +0300597 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000598
599 * choices_ - A container of the allowable values for the argument.
600
601 * required_ - Whether or not the command-line option may be omitted
602 (optionals only).
603
604 * help_ - A brief description of what the argument does.
605
606 * metavar_ - A name for the argument in usage messages.
607
608 * dest_ - The name of the attribute to be added to the object returned by
609 :meth:`parse_args`.
610
Benjamin Peterson90c58022010-03-03 01:55:09 +0000611The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000612
Georg Brandlb8d0e362010-11-26 07:53:50 +0000613
Benjamin Petersona39e9662010-03-02 22:05:59 +0000614name or flags
615^^^^^^^^^^^^^
616
Ezio Melottic69313a2011-04-22 01:29:13 +0300617The :meth:`~ArgumentParser.add_argument` method must know whether an optional
618argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
619filenames, is expected. The first arguments passed to
620:meth:`~ArgumentParser.add_argument` must therefore be either a series of
621flags, or a simple argument name. For example, an optional argument could
622be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000623
624 >>> parser.add_argument('-f', '--foo')
625
626while a positional argument could be created like::
627
628 >>> parser.add_argument('bar')
629
Ezio Melottic69313a2011-04-22 01:29:13 +0300630When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
631identified by the ``-`` prefix, and the remaining arguments will be assumed to
632be positional::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000633
634 >>> parser = argparse.ArgumentParser(prog='PROG')
635 >>> parser.add_argument('-f', '--foo')
636 >>> parser.add_argument('bar')
637 >>> parser.parse_args(['BAR'])
638 Namespace(bar='BAR', foo=None)
639 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
640 Namespace(bar='BAR', foo='FOO')
641 >>> parser.parse_args(['--foo', 'FOO'])
642 usage: PROG [-h] [-f FOO] bar
643 PROG: error: too few arguments
644
Georg Brandlb8d0e362010-11-26 07:53:50 +0000645
Benjamin Petersona39e9662010-03-02 22:05:59 +0000646action
647^^^^^^
648
Éric Araujo67719bd2011-08-19 02:00:07 +0200649:class:`ArgumentParser` objects associate command-line arguments with actions. These
650actions can do just about anything with the command-line arguments associated with
Benjamin Petersona39e9662010-03-02 22:05:59 +0000651them, though most actions simply add an attribute to the object returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300652:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Jason R. Coombs2c34fb52011-12-13 23:36:45 -0500653how the command-line arguments should be handled. The supplied actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000654
Georg Brandld2decd92010-03-02 22:17:38 +0000655* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300656 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000657
658 >>> parser = argparse.ArgumentParser()
659 >>> parser.add_argument('--foo')
660 >>> parser.parse_args('--foo 1'.split())
661 Namespace(foo='1')
662
663* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti310619c2011-04-21 23:06:48 +0300664 argument. (Note that the const_ keyword argument defaults to the rather
665 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
666 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000667
668 >>> parser = argparse.ArgumentParser()
669 >>> parser.add_argument('--foo', action='store_const', const=42)
670 >>> parser.parse_args('--foo'.split())
671 Namespace(foo=42)
672
Raymond Hettinger421467f2011-11-20 11:05:23 -0800673* ``'store_true'`` and ``'store_false'`` - These are special cases of
674 ``'store_const'`` using for storing the values ``True`` and ``False``
675 respectively. In addition, they create default values of *False* and *True*
676 respectively. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000677
678 >>> parser = argparse.ArgumentParser()
679 >>> parser.add_argument('--foo', action='store_true')
680 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettinger421467f2011-11-20 11:05:23 -0800681 >>> parser.add_argument('--baz', action='store_false')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000682 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettinger421467f2011-11-20 11:05:23 -0800683 Namespace(bar=False, baz=True, foo=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000684
685* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000686 list. This is useful to allow an option to be specified multiple times.
687 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000688
689 >>> parser = argparse.ArgumentParser()
690 >>> parser.add_argument('--foo', action='append')
691 >>> parser.parse_args('--foo 1 --foo 2'.split())
692 Namespace(foo=['1', '2'])
693
694* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000695 the const_ keyword argument to the list. (Note that the const_ keyword
696 argument defaults to ``None``.) The ``'append_const'`` action is typically
697 useful when multiple arguments need to store constants to the same list. For
698 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000699
700 >>> parser = argparse.ArgumentParser()
701 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
702 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
703 >>> parser.parse_args('--str --int'.split())
704 Namespace(types=[<type 'str'>, <type 'int'>])
705
706* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melottic69313a2011-04-22 01:29:13 +0300707 :meth:`~ArgumentParser.add_argument` call, and prints version information
708 and exits when invoked.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000709
710 >>> import argparse
711 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000712 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
713 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000714 PROG 2.0
715
Jason R. Coombs2c34fb52011-12-13 23:36:45 -0500716You may also specify an arbitrary action by passing an Action class or other
717class that implements the same interface. The recommended way to do this is
718to extend :class:`argparse.Action`, overriding the ``__call__`` method.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000719
Benjamin Peterson90c58022010-03-03 01:55:09 +0000720An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000721
722 >>> class FooAction(argparse.Action):
723 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000724 ... print '%r %r %r' % (namespace, values, option_string)
725 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000726 ...
727 >>> parser = argparse.ArgumentParser()
728 >>> parser.add_argument('--foo', action=FooAction)
729 >>> parser.add_argument('bar', action=FooAction)
730 >>> args = parser.parse_args('1 --foo 2'.split())
731 Namespace(bar=None, foo=None) '1' None
732 Namespace(bar='1', foo=None) '2' '--foo'
733 >>> args
734 Namespace(bar='1', foo='2')
735
Jason R. Coombs2c34fb52011-12-13 23:36:45 -0500736Many actions also override the ``__init__`` method, validating the parameters
737to the argument definition and raising a ValueError or other Exception on
738failure.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000739
740nargs
741^^^^^
742
743ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000744single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300745different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000746values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000747
Éric Araujo67719bd2011-08-19 02:00:07 +0200748* ``N`` (an integer). ``N`` arguments from the command line will be gathered together into a
Georg Brandld2decd92010-03-02 22:17:38 +0000749 list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000750
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000751 >>> parser = argparse.ArgumentParser()
752 >>> parser.add_argument('--foo', nargs=2)
753 >>> parser.add_argument('bar', nargs=1)
754 >>> parser.parse_args('c --foo a b'.split())
755 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000756
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000757 Note that ``nargs=1`` produces a list of one item. This is different from
758 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000759
Éric Araujo67719bd2011-08-19 02:00:07 +0200760* ``'?'``. One argument will be consumed from the command line if possible, and
761 produced as a single item. If no command-line argument is present, the value from
Benjamin Petersona39e9662010-03-02 22:05:59 +0000762 default_ will be produced. Note that for optional arguments, there is an
763 additional case - the option string is present but not followed by a
Éric Araujo67719bd2011-08-19 02:00:07 +0200764 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Petersona39e9662010-03-02 22:05:59 +0000765 examples to illustrate this::
766
Georg Brandld2decd92010-03-02 22:17:38 +0000767 >>> parser = argparse.ArgumentParser()
768 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
769 >>> parser.add_argument('bar', nargs='?', default='d')
770 >>> parser.parse_args('XX --foo YY'.split())
771 Namespace(bar='XX', foo='YY')
772 >>> parser.parse_args('XX --foo'.split())
773 Namespace(bar='XX', foo='c')
774 >>> parser.parse_args(''.split())
775 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000776
Georg Brandld2decd92010-03-02 22:17:38 +0000777 One of the more common uses of ``nargs='?'`` is to allow optional input and
778 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000779
Georg Brandld2decd92010-03-02 22:17:38 +0000780 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000781 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
782 ... default=sys.stdin)
783 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
784 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000785 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000786 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
787 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000788 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000789 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
790 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000791
Éric Araujo67719bd2011-08-19 02:00:07 +0200792* ``'*'``. All command-line arguments present are gathered into a list. Note that
Georg Brandld2decd92010-03-02 22:17:38 +0000793 it generally doesn't make much sense to have more than one positional argument
794 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
795 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000796
Georg Brandld2decd92010-03-02 22:17:38 +0000797 >>> parser = argparse.ArgumentParser()
798 >>> parser.add_argument('--foo', nargs='*')
799 >>> parser.add_argument('--bar', nargs='*')
800 >>> parser.add_argument('baz', nargs='*')
801 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
802 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000803
804* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
805 list. Additionally, an error message will be generated if there wasn't at
Éric Araujo67719bd2011-08-19 02:00:07 +0200806 least one command-line argument present. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000807
Georg Brandld2decd92010-03-02 22:17:38 +0000808 >>> parser = argparse.ArgumentParser(prog='PROG')
809 >>> parser.add_argument('foo', nargs='+')
810 >>> parser.parse_args('a b'.split())
811 Namespace(foo=['a', 'b'])
812 >>> parser.parse_args(''.split())
813 usage: PROG [-h] foo [foo ...]
814 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000815
Éric Araujo67719bd2011-08-19 02:00:07 +0200816If the ``nargs`` keyword argument is not provided, the number of arguments consumed
817is determined by the action_. Generally this means a single command-line argument
Benjamin Petersona39e9662010-03-02 22:05:59 +0000818will be consumed and a single item (not a list) will be produced.
819
820
821const
822^^^^^
823
Ezio Melottic69313a2011-04-22 01:29:13 +0300824The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
825constant values that are not read from the command line but are required for
826the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000827
Ezio Melottic69313a2011-04-22 01:29:13 +0300828* When :meth:`~ArgumentParser.add_argument` is called with
829 ``action='store_const'`` or ``action='append_const'``. These actions add the
830 ``const`` value to one of the attributes of the object returned by :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000831
Ezio Melottic69313a2011-04-22 01:29:13 +0300832* When :meth:`~ArgumentParser.add_argument` is called with option strings
833 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujo67719bd2011-08-19 02:00:07 +0200834 argument that can be followed by zero or one command-line arguments.
Ezio Melottic69313a2011-04-22 01:29:13 +0300835 When parsing the command line, if the option string is encountered with no
Éric Araujo67719bd2011-08-19 02:00:07 +0200836 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melottic69313a2011-04-22 01:29:13 +0300837 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000838
839The ``const`` keyword argument defaults to ``None``.
840
841
842default
843^^^^^^^
844
845All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300846command line. The ``default`` keyword argument of
847:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujo67719bd2011-08-19 02:00:07 +0200848specifies what value should be used if the command-line argument is not present.
Ezio Melottic69313a2011-04-22 01:29:13 +0300849For optional arguments, the ``default`` value is used when the option string
850was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000851
852 >>> parser = argparse.ArgumentParser()
853 >>> parser.add_argument('--foo', default=42)
854 >>> parser.parse_args('--foo 2'.split())
855 Namespace(foo='2')
856 >>> parser.parse_args(''.split())
857 Namespace(foo=42)
858
Éric Araujo67719bd2011-08-19 02:00:07 +0200859For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
860is used when no command-line argument was present::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000861
862 >>> parser = argparse.ArgumentParser()
863 >>> parser.add_argument('foo', nargs='?', default=42)
864 >>> parser.parse_args('a'.split())
865 Namespace(foo='a')
866 >>> parser.parse_args(''.split())
867 Namespace(foo=42)
868
869
Benjamin Peterson90c58022010-03-03 01:55:09 +0000870Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
871command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000872
873 >>> parser = argparse.ArgumentParser()
874 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
875 >>> parser.parse_args([])
876 Namespace()
877 >>> parser.parse_args(['--foo', '1'])
878 Namespace(foo='1')
879
880
881type
882^^^^
883
Éric Araujo67719bd2011-08-19 02:00:07 +0200884By default, :class:`ArgumentParser` objects read command-line arguments in as simple
885strings. However, quite often the command-line string should instead be
886interpreted as another type, like a :class:`float` or :class:`int`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300887``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujo67719bd2011-08-19 02:00:07 +0200888necessary type-checking and type conversions to be performed. Common built-in
889types and functions can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000890
891 >>> parser = argparse.ArgumentParser()
892 >>> parser.add_argument('foo', type=int)
893 >>> parser.add_argument('bar', type=file)
894 >>> parser.parse_args('2 temp.txt'.split())
895 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
896
897To ease the use of various types of files, the argparse module provides the
898factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000899``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000900writable file::
901
902 >>> parser = argparse.ArgumentParser()
903 >>> parser.add_argument('bar', type=argparse.FileType('w'))
904 >>> parser.parse_args(['out.txt'])
905 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
906
Benjamin Peterson90c58022010-03-03 01:55:09 +0000907``type=`` can take any callable that takes a single string argument and returns
Éric Araujo67719bd2011-08-19 02:00:07 +0200908the converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000909
910 >>> def perfect_square(string):
911 ... value = int(string)
912 ... sqrt = math.sqrt(value)
913 ... if sqrt != int(sqrt):
914 ... msg = "%r is not a perfect square" % string
915 ... raise argparse.ArgumentTypeError(msg)
916 ... return value
917 ...
918 >>> parser = argparse.ArgumentParser(prog='PROG')
919 >>> parser.add_argument('foo', type=perfect_square)
920 >>> parser.parse_args('9'.split())
921 Namespace(foo=9)
922 >>> parser.parse_args('7'.split())
923 usage: PROG [-h] foo
924 PROG: error: argument foo: '7' is not a perfect square
925
Benjamin Peterson90c58022010-03-03 01:55:09 +0000926The choices_ keyword argument may be more convenient for type checkers that
927simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000928
929 >>> parser = argparse.ArgumentParser(prog='PROG')
930 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
931 >>> parser.parse_args('7'.split())
932 Namespace(foo=7)
933 >>> parser.parse_args('11'.split())
934 usage: PROG [-h] {5,6,7,8,9}
935 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
936
937See the choices_ section for more details.
938
939
940choices
941^^^^^^^
942
Éric Araujo67719bd2011-08-19 02:00:07 +0200943Some command-line arguments should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000944These can be handled by passing a container object as the ``choices`` keyword
Ezio Melottic69313a2011-04-22 01:29:13 +0300945argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Éric Araujo67719bd2011-08-19 02:00:07 +0200946parsed, argument values will be checked, and an error message will be displayed if
947the argument was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000948
949 >>> parser = argparse.ArgumentParser(prog='PROG')
950 >>> parser.add_argument('foo', choices='abc')
951 >>> parser.parse_args('c'.split())
952 Namespace(foo='c')
953 >>> parser.parse_args('X'.split())
954 usage: PROG [-h] {a,b,c}
955 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
956
957Note that inclusion in the ``choices`` container is checked after any type_
958conversions have been performed, so the type of the objects in the ``choices``
959container should match the type_ specified::
960
961 >>> parser = argparse.ArgumentParser(prog='PROG')
962 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
963 >>> parser.parse_args('1j'.split())
964 Namespace(foo=1j)
965 >>> parser.parse_args('-- -4'.split())
966 usage: PROG [-h] {1,1j}
967 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
968
969Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +0000970value, so :class:`dict` objects, :class:`set` objects, custom containers,
971etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000972
973
974required
975^^^^^^^^
976
Ezio Melotti01b600c2011-04-21 16:12:17 +0300977In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +0300978indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000979To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +0300980keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000981
982 >>> parser = argparse.ArgumentParser()
983 >>> parser.add_argument('--foo', required=True)
984 >>> parser.parse_args(['--foo', 'BAR'])
985 Namespace(foo='BAR')
986 >>> parser.parse_args([])
987 usage: argparse.py [-h] [--foo FOO]
988 argparse.py: error: option --foo is required
989
Ezio Melottic69313a2011-04-22 01:29:13 +0300990As the example shows, if an option is marked as ``required``,
991:meth:`~ArgumentParser.parse_args` will report an error if that option is not
992present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000993
Benjamin Peterson90c58022010-03-03 01:55:09 +0000994.. note::
995
996 Required options are generally considered bad form because users expect
997 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000998
999
1000help
1001^^^^
1002
Benjamin Peterson90c58022010-03-03 01:55:09 +00001003The ``help`` value is a string containing a brief description of the argument.
1004When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001005command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001006argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001007
1008 >>> parser = argparse.ArgumentParser(prog='frobble')
1009 >>> parser.add_argument('--foo', action='store_true',
1010 ... help='foo the bars before frobbling')
1011 >>> parser.add_argument('bar', nargs='+',
1012 ... help='one of the bars to be frobbled')
1013 >>> parser.parse_args('-h'.split())
1014 usage: frobble [-h] [--foo] bar [bar ...]
1015
1016 positional arguments:
1017 bar one of the bars to be frobbled
1018
1019 optional arguments:
1020 -h, --help show this help message and exit
1021 --foo foo the bars before frobbling
1022
1023The ``help`` strings can include various format specifiers to avoid repetition
1024of things like the program name or the argument default_. The available
1025specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001026:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001027
1028 >>> parser = argparse.ArgumentParser(prog='frobble')
1029 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1030 ... help='the bar to %(prog)s (default: %(default)s)')
1031 >>> parser.print_help()
1032 usage: frobble [-h] [bar]
1033
1034 positional arguments:
1035 bar the bar to frobble (default: 42)
1036
1037 optional arguments:
1038 -h, --help show this help message and exit
1039
1040
1041metavar
1042^^^^^^^
1043
Benjamin Peterson90c58022010-03-03 01:55:09 +00001044When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001045to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001046value as the "name" of each object. By default, for positional argument
1047actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001048the dest_ value is uppercased. So, a single positional argument with
Eli Benderskybba1dd52011-11-11 16:42:11 +02001049``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujo67719bd2011-08-19 02:00:07 +02001050optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson90c58022010-03-03 01:55:09 +00001051will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001052
1053 >>> parser = argparse.ArgumentParser()
1054 >>> parser.add_argument('--foo')
1055 >>> parser.add_argument('bar')
1056 >>> parser.parse_args('X --foo Y'.split())
1057 Namespace(bar='X', foo='Y')
1058 >>> parser.print_help()
1059 usage: [-h] [--foo FOO] bar
1060
1061 positional arguments:
1062 bar
1063
1064 optional arguments:
1065 -h, --help show this help message and exit
1066 --foo FOO
1067
Benjamin Peterson90c58022010-03-03 01:55:09 +00001068An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001069
1070 >>> parser = argparse.ArgumentParser()
1071 >>> parser.add_argument('--foo', metavar='YYY')
1072 >>> parser.add_argument('bar', metavar='XXX')
1073 >>> parser.parse_args('X --foo Y'.split())
1074 Namespace(bar='X', foo='Y')
1075 >>> parser.print_help()
1076 usage: [-h] [--foo YYY] XXX
1077
1078 positional arguments:
1079 XXX
1080
1081 optional arguments:
1082 -h, --help show this help message and exit
1083 --foo YYY
1084
1085Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001086attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1087by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001088
1089Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001090Providing a tuple to ``metavar`` specifies a different display for each of the
1091arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001092
1093 >>> parser = argparse.ArgumentParser(prog='PROG')
1094 >>> parser.add_argument('-x', nargs=2)
1095 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1096 >>> parser.print_help()
1097 usage: PROG [-h] [-x X X] [--foo bar baz]
1098
1099 optional arguments:
1100 -h, --help show this help message and exit
1101 -x X X
1102 --foo bar baz
1103
1104
1105dest
1106^^^^
1107
Benjamin Peterson90c58022010-03-03 01:55:09 +00001108Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001109object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1110attribute is determined by the ``dest`` keyword argument of
1111:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1112``dest`` is normally supplied as the first argument to
1113:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001114
1115 >>> parser = argparse.ArgumentParser()
1116 >>> parser.add_argument('bar')
1117 >>> parser.parse_args('XXX'.split())
1118 Namespace(bar='XXX')
1119
1120For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001121the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo67719bd2011-08-19 02:00:07 +02001122taking the first long option string and stripping away the initial ``--``
Benjamin Petersona39e9662010-03-02 22:05:59 +00001123string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo67719bd2011-08-19 02:00:07 +02001124the first short option string by stripping the initial ``-`` character. Any
1125internal ``-`` characters will be converted to ``_`` characters to make sure
Georg Brandld2decd92010-03-02 22:17:38 +00001126the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001127behavior::
1128
1129 >>> parser = argparse.ArgumentParser()
1130 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1131 >>> parser.add_argument('-x', '-y')
1132 >>> parser.parse_args('-f 1 -x 2'.split())
1133 Namespace(foo_bar='1', x='2')
1134 >>> parser.parse_args('--foo 1 -y 2'.split())
1135 Namespace(foo_bar='1', x='2')
1136
Benjamin Peterson90c58022010-03-03 01:55:09 +00001137``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001138
1139 >>> parser = argparse.ArgumentParser()
1140 >>> parser.add_argument('--foo', dest='bar')
1141 >>> parser.parse_args('--foo XXX'.split())
1142 Namespace(bar='XXX')
1143
Jason R. Coombs2c34fb52011-12-13 23:36:45 -05001144Action classes
1145^^^^^^^^^^^^^^
1146
1147.. class:: Action(option_strings, dest, nargs=None, const=None, default=None,
1148 type=None, choices=None, required=False, help=None,
1149 metavar=None)
1150
1151Action objects are used by an ArgumentParser to represent the information
1152needed to parse a single argument from one or more strings from the
1153command line. The keyword arguments to the Action constructor are made
1154available as attributes of Action instances.
1155
1156* ``option_strings`` - A list of command-line option strings which
1157 should be associated with this action.
1158
1159* ``dest`` - The name of the attribute to hold the created object(s)
1160
1161* ``nargs`` - The number of command-line arguments that should be
1162 consumed. By default, one argument will be consumed and a single
1163 value will be produced. Other values include:
1164 - N (an integer) consumes N arguments (and produces a list)
1165 - '?' consumes zero or one arguments
1166 - '*' consumes zero or more arguments (and produces a list)
1167 - '+' consumes one or more arguments (and produces a list)
1168 Note that the difference between the default and nargs=1 is that
1169 with the default, a single value will be produced, while with
1170 nargs=1, a list containing a single value will be produced.
1171
1172* ``const`` - The value to be produced if the option is specified and the
1173 option uses an action that takes no values.
1174
1175* ``default`` - The value to be produced if the option is not specified.
1176
1177* ``type`` - The type which the command-line arguments should be converted
1178 to, should be one of 'string', 'int', 'float', 'complex' or a
1179 callable object that accepts a single string argument. If None,
1180 'string' is assumed.
1181
1182* ``choices`` - A container of values that should be allowed. If not None,
1183 after a command-line argument has been converted to the appropriate
1184 type, an exception will be raised if it is not a member of this
1185 collection.
1186
1187* ``required`` - True if the action must always be specified at the
1188 command line. This is only meaningful for optional command-line
1189 arguments.
1190
1191* ``help`` - The help string describing the argument.
1192
1193* ``metavar`` - The name to be used for the option's argument with the
1194 help string. If None, the 'dest' value will be used as the name.
1195
1196Action classes must also override the ``__call__`` method, which should accept
1197four parameters:
1198
1199* ``parser`` - The ArgumentParser object which contains this action.
1200
1201* ``namespace`` - The :class:`Namespace` object that will be returned by
1202 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
1203 object using :func:`setattr`.
1204
1205* ``values`` - The associated command-line arguments, with any type conversions
1206 applied. Type conversions are specified with the type_ keyword argument to
1207 :meth:`~ArgumentParser.add_argument`.
1208
1209* ``option_string`` - The option string that was used to invoke this action.
1210 The ``option_string`` argument is optional, and will be absent if the action
1211 is associated with a positional argument.
1212
Benjamin Petersona39e9662010-03-02 22:05:59 +00001213
1214The parse_args() method
1215-----------------------
1216
Georg Brandlb8d0e362010-11-26 07:53:50 +00001217.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001218
Benjamin Peterson90c58022010-03-03 01:55:09 +00001219 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001220 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001221
1222 Previous calls to :meth:`add_argument` determine exactly what objects are
1223 created and how they are assigned. See the documentation for
1224 :meth:`add_argument` for details.
1225
Éric Araujo67719bd2011-08-19 02:00:07 +02001226 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001227 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001228
Georg Brandlb8d0e362010-11-26 07:53:50 +00001229
Benjamin Petersona39e9662010-03-02 22:05:59 +00001230Option value syntax
1231^^^^^^^^^^^^^^^^^^^
1232
Ezio Melottic69313a2011-04-22 01:29:13 +03001233The :meth:`~ArgumentParser.parse_args` method supports several ways of
1234specifying the value of an option (if it takes one). In the simplest case, the
1235option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001236
1237 >>> parser = argparse.ArgumentParser(prog='PROG')
1238 >>> parser.add_argument('-x')
1239 >>> parser.add_argument('--foo')
1240 >>> parser.parse_args('-x X'.split())
1241 Namespace(foo=None, x='X')
1242 >>> parser.parse_args('--foo FOO'.split())
1243 Namespace(foo='FOO', x=None)
1244
Benjamin Peterson90c58022010-03-03 01:55:09 +00001245For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001246and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001247separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001248
1249 >>> parser.parse_args('--foo=FOO'.split())
1250 Namespace(foo='FOO', x=None)
1251
Benjamin Peterson90c58022010-03-03 01:55:09 +00001252For short options (options only one character long), the option and its value
1253can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001254
1255 >>> parser.parse_args('-xX'.split())
1256 Namespace(foo=None, x='X')
1257
Benjamin Peterson90c58022010-03-03 01:55:09 +00001258Several short options can be joined together, using only a single ``-`` prefix,
1259as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001260
1261 >>> parser = argparse.ArgumentParser(prog='PROG')
1262 >>> parser.add_argument('-x', action='store_true')
1263 >>> parser.add_argument('-y', action='store_true')
1264 >>> parser.add_argument('-z')
1265 >>> parser.parse_args('-xyzZ'.split())
1266 Namespace(x=True, y=True, z='Z')
1267
1268
1269Invalid arguments
1270^^^^^^^^^^^^^^^^^
1271
Ezio Melottic69313a2011-04-22 01:29:13 +03001272While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1273variety of errors, including ambiguous options, invalid types, invalid options,
1274wrong number of positional arguments, etc. When it encounters such an error,
1275it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001276
1277 >>> parser = argparse.ArgumentParser(prog='PROG')
1278 >>> parser.add_argument('--foo', type=int)
1279 >>> parser.add_argument('bar', nargs='?')
1280
1281 >>> # invalid type
1282 >>> parser.parse_args(['--foo', 'spam'])
1283 usage: PROG [-h] [--foo FOO] [bar]
1284 PROG: error: argument --foo: invalid int value: 'spam'
1285
1286 >>> # invalid option
1287 >>> parser.parse_args(['--bar'])
1288 usage: PROG [-h] [--foo FOO] [bar]
1289 PROG: error: no such option: --bar
1290
1291 >>> # wrong number of arguments
1292 >>> parser.parse_args(['spam', 'badger'])
1293 usage: PROG [-h] [--foo FOO] [bar]
1294 PROG: error: extra arguments found: badger
1295
1296
Éric Araujo67719bd2011-08-19 02:00:07 +02001297Arguments containing ``-``
1298^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001299
Ezio Melottic69313a2011-04-22 01:29:13 +03001300The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1301the user has clearly made a mistake, but some situations are inherently
Éric Araujo67719bd2011-08-19 02:00:07 +02001302ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melottic69313a2011-04-22 01:29:13 +03001303attempt to specify an option or an attempt to provide a positional argument.
1304The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo67719bd2011-08-19 02:00:07 +02001305arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melottic69313a2011-04-22 01:29:13 +03001306there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001307
1308 >>> parser = argparse.ArgumentParser(prog='PROG')
1309 >>> parser.add_argument('-x')
1310 >>> parser.add_argument('foo', nargs='?')
1311
1312 >>> # no negative number options, so -1 is a positional argument
1313 >>> parser.parse_args(['-x', '-1'])
1314 Namespace(foo=None, x='-1')
1315
1316 >>> # no negative number options, so -1 and -5 are positional arguments
1317 >>> parser.parse_args(['-x', '-1', '-5'])
1318 Namespace(foo='-5', x='-1')
1319
1320 >>> parser = argparse.ArgumentParser(prog='PROG')
1321 >>> parser.add_argument('-1', dest='one')
1322 >>> parser.add_argument('foo', nargs='?')
1323
1324 >>> # negative number options present, so -1 is an option
1325 >>> parser.parse_args(['-1', 'X'])
1326 Namespace(foo=None, one='X')
1327
1328 >>> # negative number options present, so -2 is an option
1329 >>> parser.parse_args(['-2'])
1330 usage: PROG [-h] [-1 ONE] [foo]
1331 PROG: error: no such option: -2
1332
1333 >>> # negative number options present, so both -1s are options
1334 >>> parser.parse_args(['-1', '-1'])
1335 usage: PROG [-h] [-1 ONE] [foo]
1336 PROG: error: argument -1: expected one argument
1337
Éric Araujo67719bd2011-08-19 02:00:07 +02001338If you have positional arguments that must begin with ``-`` and don't look
Benjamin Petersona39e9662010-03-02 22:05:59 +00001339like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001340:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1341argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001342
1343 >>> parser.parse_args(['--', '-f'])
1344 Namespace(foo='-f', one=None)
1345
1346
1347Argument abbreviations
1348^^^^^^^^^^^^^^^^^^^^^^
1349
Ezio Melottic69313a2011-04-22 01:29:13 +03001350The :meth:`~ArgumentParser.parse_args` method allows long options to be
1351abbreviated if the abbreviation is unambiguous::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001352
1353 >>> parser = argparse.ArgumentParser(prog='PROG')
1354 >>> parser.add_argument('-bacon')
1355 >>> parser.add_argument('-badger')
1356 >>> parser.parse_args('-bac MMM'.split())
1357 Namespace(bacon='MMM', badger=None)
1358 >>> parser.parse_args('-bad WOOD'.split())
1359 Namespace(bacon=None, badger='WOOD')
1360 >>> parser.parse_args('-ba BA'.split())
1361 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1362 PROG: error: ambiguous option: -ba could match -badger, -bacon
1363
Benjamin Peterson90c58022010-03-03 01:55:09 +00001364An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001365
1366
1367Beyond ``sys.argv``
1368^^^^^^^^^^^^^^^^^^^
1369
Éric Araujo67719bd2011-08-19 02:00:07 +02001370Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Georg Brandld2decd92010-03-02 22:17:38 +00001371of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001372:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1373interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001374
1375 >>> parser = argparse.ArgumentParser()
1376 >>> parser.add_argument(
1377 ... 'integers', metavar='int', type=int, choices=xrange(10),
1378 ... nargs='+', help='an integer in the range 0..9')
1379 >>> parser.add_argument(
1380 ... '--sum', dest='accumulate', action='store_const', const=sum,
1381 ... default=max, help='sum the integers (default: find the max)')
1382 >>> parser.parse_args(['1', '2', '3', '4'])
1383 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1384 >>> parser.parse_args('1 2 3 4 --sum'.split())
1385 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1386
1387
Steven Bethard3f69a052011-03-26 19:59:02 +01001388The Namespace object
1389^^^^^^^^^^^^^^^^^^^^
1390
Éric Araujof0d44bc2011-07-29 17:59:17 +02001391.. class:: Namespace
1392
1393 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1394 an object holding attributes and return it.
1395
1396This class is deliberately simple, just an :class:`object` subclass with a
1397readable string representation. If you prefer to have dict-like view of the
1398attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001399
1400 >>> parser = argparse.ArgumentParser()
1401 >>> parser.add_argument('--foo')
1402 >>> args = parser.parse_args(['--foo', 'BAR'])
1403 >>> vars(args)
1404 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001405
Benjamin Peterson90c58022010-03-03 01:55:09 +00001406It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001407already existing object, rather than a new :class:`Namespace` object. This can
1408be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001409
1410 >>> class C(object):
1411 ... pass
1412 ...
1413 >>> c = C()
1414 >>> parser = argparse.ArgumentParser()
1415 >>> parser.add_argument('--foo')
1416 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1417 >>> c.foo
1418 'BAR'
1419
1420
1421Other utilities
1422---------------
1423
1424Sub-commands
1425^^^^^^^^^^^^
1426
Benjamin Peterson90c58022010-03-03 01:55:09 +00001427.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001428
Benjamin Peterson90c58022010-03-03 01:55:09 +00001429 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001430 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001431 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001432 this way can be a particularly good idea when a program performs several
1433 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001434 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001435 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1436 called with no arguments and returns an special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001437 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1438 command name and any :class:`ArgumentParser` constructor arguments, and
1439 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001440
1441 Some example usage::
1442
1443 >>> # create the top-level parser
1444 >>> parser = argparse.ArgumentParser(prog='PROG')
1445 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1446 >>> subparsers = parser.add_subparsers(help='sub-command help')
1447 >>>
1448 >>> # create the parser for the "a" command
1449 >>> parser_a = subparsers.add_parser('a', help='a help')
1450 >>> parser_a.add_argument('bar', type=int, help='bar help')
1451 >>>
1452 >>> # create the parser for the "b" command
1453 >>> parser_b = subparsers.add_parser('b', help='b help')
1454 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1455 >>>
Éric Araujo67719bd2011-08-19 02:00:07 +02001456 >>> # parse some argument lists
Benjamin Petersona39e9662010-03-02 22:05:59 +00001457 >>> parser.parse_args(['a', '12'])
1458 Namespace(bar=12, foo=False)
1459 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1460 Namespace(baz='Z', foo=True)
1461
1462 Note that the object returned by :meth:`parse_args` will only contain
1463 attributes for the main parser and the subparser that was selected by the
1464 command line (and not any other subparsers). So in the example above, when
Éric Araujo67719bd2011-08-19 02:00:07 +02001465 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1466 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001467 ``baz`` attributes are present.
1468
1469 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001470 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001471 include parent parser or sibling parser messages. (A help message for each
1472 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001473 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001474
1475 ::
1476
1477 >>> parser.parse_args(['--help'])
1478 usage: PROG [-h] [--foo] {a,b} ...
1479
1480 positional arguments:
1481 {a,b} sub-command help
1482 a a help
1483 b b help
1484
1485 optional arguments:
1486 -h, --help show this help message and exit
1487 --foo foo help
1488
1489 >>> parser.parse_args(['a', '--help'])
1490 usage: PROG a [-h] bar
1491
1492 positional arguments:
1493 bar bar help
1494
1495 optional arguments:
1496 -h, --help show this help message and exit
1497
1498 >>> parser.parse_args(['b', '--help'])
1499 usage: PROG b [-h] [--baz {X,Y,Z}]
1500
1501 optional arguments:
1502 -h, --help show this help message and exit
1503 --baz {X,Y,Z} baz help
1504
Georg Brandld2decd92010-03-02 22:17:38 +00001505 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1506 keyword arguments. When either is present, the subparser's commands will
1507 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001508
1509 >>> parser = argparse.ArgumentParser()
1510 >>> subparsers = parser.add_subparsers(title='subcommands',
1511 ... description='valid subcommands',
1512 ... help='additional help')
1513 >>> subparsers.add_parser('foo')
1514 >>> subparsers.add_parser('bar')
1515 >>> parser.parse_args(['-h'])
1516 usage: [-h] {foo,bar} ...
1517
1518 optional arguments:
1519 -h, --help show this help message and exit
1520
1521 subcommands:
1522 valid subcommands
1523
1524 {foo,bar} additional help
1525
1526
Georg Brandld2decd92010-03-02 22:17:38 +00001527 One particularly effective way of handling sub-commands is to combine the use
1528 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1529 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001530 example::
1531
1532 >>> # sub-command functions
1533 >>> def foo(args):
1534 ... print args.x * args.y
1535 ...
1536 >>> def bar(args):
1537 ... print '((%s))' % args.z
1538 ...
1539 >>> # create the top-level parser
1540 >>> parser = argparse.ArgumentParser()
1541 >>> subparsers = parser.add_subparsers()
1542 >>>
1543 >>> # create the parser for the "foo" command
1544 >>> parser_foo = subparsers.add_parser('foo')
1545 >>> parser_foo.add_argument('-x', type=int, default=1)
1546 >>> parser_foo.add_argument('y', type=float)
1547 >>> parser_foo.set_defaults(func=foo)
1548 >>>
1549 >>> # create the parser for the "bar" command
1550 >>> parser_bar = subparsers.add_parser('bar')
1551 >>> parser_bar.add_argument('z')
1552 >>> parser_bar.set_defaults(func=bar)
1553 >>>
1554 >>> # parse the args and call whatever function was selected
1555 >>> args = parser.parse_args('foo 1 -x 2'.split())
1556 >>> args.func(args)
1557 2.0
1558 >>>
1559 >>> # parse the args and call whatever function was selected
1560 >>> args = parser.parse_args('bar XYZYX'.split())
1561 >>> args.func(args)
1562 ((XYZYX))
1563
Benjamin Peterson90c58022010-03-03 01:55:09 +00001564 This way, you can let :meth:`parse_args` does the job of calling the
1565 appropriate function after argument parsing is complete. Associating
1566 functions with actions like this is typically the easiest way to handle the
1567 different actions for each of your subparsers. However, if it is necessary
1568 to check the name of the subparser that was invoked, the ``dest`` keyword
1569 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001570
1571 >>> parser = argparse.ArgumentParser()
1572 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1573 >>> subparser1 = subparsers.add_parser('1')
1574 >>> subparser1.add_argument('-x')
1575 >>> subparser2 = subparsers.add_parser('2')
1576 >>> subparser2.add_argument('y')
1577 >>> parser.parse_args(['2', 'frobble'])
1578 Namespace(subparser_name='2', y='frobble')
1579
1580
1581FileType objects
1582^^^^^^^^^^^^^^^^
1583
1584.. class:: FileType(mode='r', bufsize=None)
1585
1586 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001587 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujo67719bd2011-08-19 02:00:07 +02001588 :class:`FileType` objects as their type will open command-line arguments as files
Benjamin Peterson90c58022010-03-03 01:55:09 +00001589 with the requested modes and buffer sizes:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001590
1591 >>> parser = argparse.ArgumentParser()
1592 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1593 >>> parser.parse_args(['--output', 'out'])
1594 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1595
1596 FileType objects understand the pseudo-argument ``'-'`` and automatically
1597 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1598 ``sys.stdout`` for writable :class:`FileType` objects:
1599
1600 >>> parser = argparse.ArgumentParser()
1601 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1602 >>> parser.parse_args(['-'])
1603 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1604
1605
1606Argument groups
1607^^^^^^^^^^^^^^^
1608
Georg Brandlb8d0e362010-11-26 07:53:50 +00001609.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001610
Benjamin Peterson90c58022010-03-03 01:55:09 +00001611 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001612 "positional arguments" and "optional arguments" when displaying help
1613 messages. When there is a better conceptual grouping of arguments than this
1614 default one, appropriate groups can be created using the
1615 :meth:`add_argument_group` method::
1616
1617 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1618 >>> group = parser.add_argument_group('group')
1619 >>> group.add_argument('--foo', help='foo help')
1620 >>> group.add_argument('bar', help='bar help')
1621 >>> parser.print_help()
1622 usage: PROG [--foo FOO] bar
1623
1624 group:
1625 bar bar help
1626 --foo FOO foo help
1627
1628 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001629 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1630 :class:`ArgumentParser`. When an argument is added to the group, the parser
1631 treats it just like a normal argument, but displays the argument in a
1632 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001633 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001634 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001635
1636 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1637 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1638 >>> group1.add_argument('foo', help='foo help')
1639 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1640 >>> group2.add_argument('--bar', help='bar help')
1641 >>> parser.print_help()
1642 usage: PROG [--bar BAR] foo
1643
1644 group1:
1645 group1 description
1646
1647 foo foo help
1648
1649 group2:
1650 group2 description
1651
1652 --bar BAR bar help
1653
Benjamin Peterson90c58022010-03-03 01:55:09 +00001654 Note that any arguments not your user defined groups will end up back in the
1655 usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001656
1657
1658Mutual exclusion
1659^^^^^^^^^^^^^^^^
1660
Georg Brandlb8d0e362010-11-26 07:53:50 +00001661.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001662
Ezio Melotti01b600c2011-04-21 16:12:17 +03001663 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1664 one of the arguments in the mutually exclusive group was present on the
1665 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001666
1667 >>> parser = argparse.ArgumentParser(prog='PROG')
1668 >>> group = parser.add_mutually_exclusive_group()
1669 >>> group.add_argument('--foo', action='store_true')
1670 >>> group.add_argument('--bar', action='store_false')
1671 >>> parser.parse_args(['--foo'])
1672 Namespace(bar=True, foo=True)
1673 >>> parser.parse_args(['--bar'])
1674 Namespace(bar=False, foo=False)
1675 >>> parser.parse_args(['--foo', '--bar'])
1676 usage: PROG [-h] [--foo | --bar]
1677 PROG: error: argument --bar: not allowed with argument --foo
1678
Georg Brandlb8d0e362010-11-26 07:53:50 +00001679 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001680 argument, to indicate that at least one of the mutually exclusive arguments
1681 is required::
1682
1683 >>> parser = argparse.ArgumentParser(prog='PROG')
1684 >>> group = parser.add_mutually_exclusive_group(required=True)
1685 >>> group.add_argument('--foo', action='store_true')
1686 >>> group.add_argument('--bar', action='store_false')
1687 >>> parser.parse_args([])
1688 usage: PROG [-h] (--foo | --bar)
1689 PROG: error: one of the arguments --foo --bar is required
1690
1691 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001692 *title* and *description* arguments of
1693 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001694
1695
1696Parser defaults
1697^^^^^^^^^^^^^^^
1698
Benjamin Peterson90c58022010-03-03 01:55:09 +00001699.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001700
Georg Brandld2decd92010-03-02 22:17:38 +00001701 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujo67719bd2011-08-19 02:00:07 +02001702 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001703 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001704 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001705 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001706
1707 >>> parser = argparse.ArgumentParser()
1708 >>> parser.add_argument('foo', type=int)
1709 >>> parser.set_defaults(bar=42, baz='badger')
1710 >>> parser.parse_args(['736'])
1711 Namespace(bar=42, baz='badger', foo=736)
1712
Benjamin Peterson90c58022010-03-03 01:55:09 +00001713 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001714
1715 >>> parser = argparse.ArgumentParser()
1716 >>> parser.add_argument('--foo', default='bar')
1717 >>> parser.set_defaults(foo='spam')
1718 >>> parser.parse_args([])
1719 Namespace(foo='spam')
1720
Benjamin Peterson90c58022010-03-03 01:55:09 +00001721 Parser-level defaults can be particularly useful when working with multiple
1722 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1723 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001724
Benjamin Peterson90c58022010-03-03 01:55:09 +00001725.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001726
1727 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001728 :meth:`~ArgumentParser.add_argument` or by
1729 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001730
1731 >>> parser = argparse.ArgumentParser()
1732 >>> parser.add_argument('--foo', default='badger')
1733 >>> parser.get_default('foo')
1734 'badger'
1735
1736
1737Printing help
1738^^^^^^^^^^^^^
1739
Ezio Melottic69313a2011-04-22 01:29:13 +03001740In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1741care of formatting and printing any usage or error messages. However, several
1742formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001743
Georg Brandlb8d0e362010-11-26 07:53:50 +00001744.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001745
1746 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001747 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001748 assumed.
1749
Georg Brandlb8d0e362010-11-26 07:53:50 +00001750.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001751
1752 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001753 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001754 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001755
1756There are also variants of these methods that simply return a string instead of
1757printing it:
1758
Georg Brandlb8d0e362010-11-26 07:53:50 +00001759.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001760
1761 Return a string containing a brief description of how the
1762 :class:`ArgumentParser` should be invoked on the command line.
1763
Georg Brandlb8d0e362010-11-26 07:53:50 +00001764.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001765
1766 Return a string containing a help message, including the program usage and
1767 information about the arguments registered with the :class:`ArgumentParser`.
1768
1769
Benjamin Petersona39e9662010-03-02 22:05:59 +00001770Partial parsing
1771^^^^^^^^^^^^^^^
1772
Georg Brandlb8d0e362010-11-26 07:53:50 +00001773.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001774
Ezio Melotti12125822011-04-16 23:04:51 +03001775Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001776the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001777:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001778:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1779extra arguments are present. Instead, it returns a two item tuple containing
1780the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001781
1782::
1783
1784 >>> parser = argparse.ArgumentParser()
1785 >>> parser.add_argument('--foo', action='store_true')
1786 >>> parser.add_argument('bar')
1787 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1788 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1789
1790
1791Customizing file parsing
1792^^^^^^^^^^^^^^^^^^^^^^^^
1793
Benjamin Peterson90c58022010-03-03 01:55:09 +00001794.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001795
Georg Brandlb8d0e362010-11-26 07:53:50 +00001796 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001797 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001798 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1799 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001800
Georg Brandlb8d0e362010-11-26 07:53:50 +00001801 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001802 the argument file. It returns a list of arguments parsed from this string.
1803 The method is called once per line read from the argument file, in order.
1804
Georg Brandld2decd92010-03-02 22:17:38 +00001805 A useful override of this method is one that treats each space-separated word
1806 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001807
1808 def convert_arg_line_to_args(self, arg_line):
1809 for arg in arg_line.split():
1810 if not arg.strip():
1811 continue
1812 yield arg
1813
1814
Georg Brandlb8d0e362010-11-26 07:53:50 +00001815Exiting methods
1816^^^^^^^^^^^^^^^
1817
1818.. method:: ArgumentParser.exit(status=0, message=None)
1819
1820 This method terminates the program, exiting with the specified *status*
1821 and, if given, it prints a *message* before that.
1822
1823.. method:: ArgumentParser.error(message)
1824
1825 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001826 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001827
1828
Georg Brandl58df6792010-07-03 10:25:47 +00001829.. _argparse-from-optparse:
1830
Benjamin Petersona39e9662010-03-02 22:05:59 +00001831Upgrading optparse code
1832-----------------------
1833
Ezio Melottic69313a2011-04-22 01:29:13 +03001834Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001835with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1836transparently, particularly with the changes required to support the new
1837``nargs=`` specifiers and better usage messages. When most everything in
1838:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1839longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001840
Ezio Melotti01b600c2011-04-21 16:12:17 +03001841A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001842
Ezio Melottic69313a2011-04-22 01:29:13 +03001843* Replace all :meth:`optparse.OptionParser.add_option` calls with
1844 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001845
Georg Brandld2decd92010-03-02 22:17:38 +00001846* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001847 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1848 calls for the positional arguments.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001849
1850* Replace callback actions and the ``callback_*`` keyword arguments with
1851 ``type`` or ``action`` arguments.
1852
1853* Replace string names for ``type`` keyword arguments with the corresponding
1854 type objects (e.g. int, float, complex, etc).
1855
Benjamin Peterson90c58022010-03-03 01:55:09 +00001856* Replace :class:`optparse.Values` with :class:`Namespace` and
1857 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1858 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001859
Georg Brandld2decd92010-03-02 22:17:38 +00001860* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001861 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001862 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001863
1864* Replace the OptionParser constructor ``version`` argument with a call to
1865 ``parser.add_argument('--version', action='version', version='<the version>')``