blob: 50a453341680e02fbc362a9eb6bfcaa8c5dec8fe [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
Éric Araujobb42f5e2012-02-20 02:08:01 +0100127.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
128 [argument_default], [parents], [prefix_chars], \
129 [conflict_handler], [formatter_class])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000130
Georg Brandld2decd92010-03-02 22:17:38 +0000131 Create a new :class:`ArgumentParser` object. Each parameter has its own more
Benjamin Petersona39e9662010-03-02 22:05:59 +0000132 detailed description below, but in short they are:
133
134 * description_ - Text to display before the argument help.
135
136 * epilog_ - Text to display after the argument help.
137
Benjamin Peterson90c58022010-03-03 01:55:09 +0000138 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000139
140 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000141 (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000142
Benjamin Peterson90c58022010-03-03 01:55:09 +0000143 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Petersona39e9662010-03-02 22:05:59 +0000144 also be included.
145
146 * prefix_chars_ - The set of characters that prefix optional arguments.
147 (default: '-')
148
149 * fromfile_prefix_chars_ - The set of characters that prefix files from
Benjamin Peterson90c58022010-03-03 01:55:09 +0000150 which additional arguments should be read. (default: ``None``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000151
152 * formatter_class_ - A class for customizing the help output.
153
154 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
155 conflicting optionals.
156
Benjamin Peterson90c58022010-03-03 01:55:09 +0000157 * prog_ - The name of the program (default:
Éric Araujo7ce05e02011-09-01 19:54:05 +0200158 ``sys.argv[0]``)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000159
Benjamin Peterson90c58022010-03-03 01:55:09 +0000160 * usage_ - The string describing the program usage (default: generated)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000161
Benjamin Peterson90c58022010-03-03 01:55:09 +0000162The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000163
164
165description
166^^^^^^^^^^^
167
Benjamin Peterson90c58022010-03-03 01:55:09 +0000168Most calls to the :class:`ArgumentParser` constructor will use the
169``description=`` keyword argument. This argument gives a brief description of
170what the program does and how it works. In help messages, the description is
171displayed between the command-line usage string and the help messages for the
172various arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000173
174 >>> parser = argparse.ArgumentParser(description='A foo that bars')
175 >>> parser.print_help()
176 usage: argparse.py [-h]
177
178 A foo that bars
179
180 optional arguments:
181 -h, --help show this help message and exit
182
183By default, the description will be line-wrapped so that it fits within the
Georg Brandld2decd92010-03-02 22:17:38 +0000184given space. To change this behavior, see the formatter_class_ argument.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000185
186
187epilog
188^^^^^^
189
190Some programs like to display additional description of the program after the
Georg Brandld2decd92010-03-02 22:17:38 +0000191description of the arguments. Such text can be specified using the ``epilog=``
192argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000193
194 >>> parser = argparse.ArgumentParser(
195 ... description='A foo that bars',
196 ... epilog="And that's how you'd foo a bar")
197 >>> parser.print_help()
198 usage: argparse.py [-h]
199
200 A foo that bars
201
202 optional arguments:
203 -h, --help show this help message and exit
204
205 And that's how you'd foo a bar
206
207As with the description_ argument, the ``epilog=`` text is by default
208line-wrapped, but this behavior can be adjusted with the formatter_class_
Benjamin Peterson90c58022010-03-03 01:55:09 +0000209argument to :class:`ArgumentParser`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000210
211
212add_help
213^^^^^^^^
214
R. David Murray1cbf78e2010-08-03 18:14:01 +0000215By default, ArgumentParser objects add an option which simply displays
216the parser's help message. For example, consider a file named
Benjamin Petersona39e9662010-03-02 22:05:59 +0000217``myprogram.py`` containing the following code::
218
219 import argparse
220 parser = argparse.ArgumentParser()
221 parser.add_argument('--foo', help='foo help')
222 args = parser.parse_args()
223
Ezio Melotti12125822011-04-16 23:04:51 +0300224If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Petersona39e9662010-03-02 22:05:59 +0000225help will be printed::
226
227 $ python myprogram.py --help
228 usage: myprogram.py [-h] [--foo FOO]
229
230 optional arguments:
231 -h, --help show this help message and exit
232 --foo FOO foo help
233
234Occasionally, it may be useful to disable the addition of this help option.
235This can be achieved by passing ``False`` as the ``add_help=`` argument to
Benjamin Peterson90c58022010-03-03 01:55:09 +0000236:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000237
238 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
239 >>> parser.add_argument('--foo', help='foo help')
240 >>> parser.print_help()
241 usage: PROG [--foo FOO]
242
243 optional arguments:
244 --foo FOO foo help
245
R. David Murray1cbf78e2010-08-03 18:14:01 +0000246The help option is typically ``-h/--help``. The exception to this is
Éric Araujo67719bd2011-08-19 02:00:07 +0200247if the ``prefix_chars=`` is specified and does not include ``-``, in
R. David Murray1cbf78e2010-08-03 18:14:01 +0000248which case ``-h`` and ``--help`` are not valid options. In
249this case, the first character in ``prefix_chars`` is used to prefix
250the help options::
251
252 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
253 >>> parser.print_help()
254 usage: PROG [+h]
255
256 optional arguments:
257 +h, ++help show this help message and exit
258
259
Benjamin Petersona39e9662010-03-02 22:05:59 +0000260prefix_chars
261^^^^^^^^^^^^
262
Éric Araujo67719bd2011-08-19 02:00:07 +0200263Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
R. David Murray1cbf78e2010-08-03 18:14:01 +0000264Parsers that need to support different or additional prefix
265characters, e.g. for options
Benjamin Petersona39e9662010-03-02 22:05:59 +0000266like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
267to the ArgumentParser constructor::
268
269 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
270 >>> parser.add_argument('+f')
271 >>> parser.add_argument('++bar')
272 >>> parser.parse_args('+f X ++bar Y'.split())
273 Namespace(bar='Y', f='X')
274
275The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
Éric Araujo67719bd2011-08-19 02:00:07 +0200276characters that does not include ``-`` will cause ``-f/--foo`` options to be
Benjamin Petersona39e9662010-03-02 22:05:59 +0000277disallowed.
278
279
280fromfile_prefix_chars
281^^^^^^^^^^^^^^^^^^^^^
282
Benjamin Peterson90c58022010-03-03 01:55:09 +0000283Sometimes, for example when dealing with a particularly long argument lists, it
284may make sense to keep the list of arguments in a file rather than typing it out
285at the command line. If the ``fromfile_prefix_chars=`` argument is given to the
286:class:`ArgumentParser` constructor, then arguments that start with any of the
287specified characters will be treated as files, and will be replaced by the
288arguments they contain. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000289
Benjamin Peterson90c58022010-03-03 01:55:09 +0000290 >>> with open('args.txt', 'w') as fp:
291 ... fp.write('-f\nbar')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000292 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
293 >>> parser.add_argument('-f')
294 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
295 Namespace(f='bar')
296
297Arguments read from a file must by default be one per line (but see also
Ezio Melottic69313a2011-04-22 01:29:13 +0300298:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
299were in the same place as the original file referencing argument on the command
300line. So in the example above, the expression ``['-f', 'foo', '@args.txt']``
301is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000302
303The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
304arguments will never be treated as file references.
305
Georg Brandlb8d0e362010-11-26 07:53:50 +0000306
Benjamin Petersona39e9662010-03-02 22:05:59 +0000307argument_default
308^^^^^^^^^^^^^^^^
309
310Generally, argument defaults are specified either by passing a default to
Ezio Melottic69313a2011-04-22 01:29:13 +0300311:meth:`~ArgumentParser.add_argument` or by calling the
312:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
313pairs. Sometimes however, it may be useful to specify a single parser-wide
314default for arguments. This can be accomplished by passing the
315``argument_default=`` keyword argument to :class:`ArgumentParser`. For example,
316to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
Benjamin Peterson90c58022010-03-03 01:55:09 +0000317calls, we supply ``argument_default=SUPPRESS``::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000318
319 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
320 >>> parser.add_argument('--foo')
321 >>> parser.add_argument('bar', nargs='?')
322 >>> parser.parse_args(['--foo', '1', 'BAR'])
323 Namespace(bar='BAR', foo='1')
324 >>> parser.parse_args([])
325 Namespace()
326
327
328parents
329^^^^^^^
330
331Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson90c58022010-03-03 01:55:09 +0000332repeating the definitions of these arguments, a single parser with all the
333shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
334can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
335objects, collects all the positional and optional actions from them, and adds
336these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000337
338 >>> parent_parser = argparse.ArgumentParser(add_help=False)
339 >>> parent_parser.add_argument('--parent', type=int)
340
341 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
342 >>> foo_parser.add_argument('foo')
343 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
344 Namespace(foo='XXX', parent=2)
345
346 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
347 >>> bar_parser.add_argument('--bar')
348 >>> bar_parser.parse_args(['--bar', 'YYY'])
349 Namespace(bar='YYY', parent=None)
350
Georg Brandld2decd92010-03-02 22:17:38 +0000351Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000352:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
353and one in the child) and raise an error.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000354
Steven Bethard5e0062d2011-03-26 21:50:38 +0100355.. note::
356 You must fully initialize the parsers before passing them via ``parents=``.
357 If you change the parent parsers after the child parser, those changes will
358 not be reflected in the child.
359
Benjamin Petersona39e9662010-03-02 22:05:59 +0000360
361formatter_class
362^^^^^^^^^^^^^^^
363
Benjamin Peterson90c58022010-03-03 01:55:09 +0000364:class:`ArgumentParser` objects allow the help formatting to be customized by
365specifying an alternate formatting class. Currently, there are three such
Ezio Melottic69313a2011-04-22 01:29:13 +0300366classes:
367
368.. class:: RawDescriptionHelpFormatter
369 RawTextHelpFormatter
370 ArgumentDefaultsHelpFormatter
371
372The first two allow more control over how textual descriptions are displayed,
373while the last automatically adds information about argument default values.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000374
Benjamin Peterson90c58022010-03-03 01:55:09 +0000375By default, :class:`ArgumentParser` objects line-wrap the description_ and
376epilog_ texts in command-line help messages::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000377
378 >>> parser = argparse.ArgumentParser(
379 ... prog='PROG',
380 ... description='''this description
381 ... was indented weird
382 ... but that is okay''',
383 ... epilog='''
384 ... likewise for this epilog whose whitespace will
385 ... be cleaned up and whose words will be wrapped
386 ... across a couple lines''')
387 >>> parser.print_help()
388 usage: PROG [-h]
389
390 this description was indented weird but that is okay
391
392 optional arguments:
393 -h, --help show this help message and exit
394
395 likewise for this epilog whose whitespace will be cleaned up and whose words
396 will be wrapped across a couple lines
397
Éric Araujo67719bd2011-08-19 02:00:07 +0200398Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Petersonc516d192010-03-03 02:04:24 +0000399indicates that description_ and epilog_ are already correctly formatted and
Benjamin Peterson90c58022010-03-03 01:55:09 +0000400should not be line-wrapped::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000401
402 >>> parser = argparse.ArgumentParser(
403 ... prog='PROG',
404 ... formatter_class=argparse.RawDescriptionHelpFormatter,
405 ... description=textwrap.dedent('''\
406 ... Please do not mess up this text!
407 ... --------------------------------
408 ... I have indented it
409 ... exactly the way
410 ... I want it
411 ... '''))
412 >>> parser.print_help()
413 usage: PROG [-h]
414
415 Please do not mess up this text!
416 --------------------------------
417 I have indented it
418 exactly the way
419 I want it
420
421 optional arguments:
422 -h, --help show this help message and exit
423
Éric Araujo67719bd2011-08-19 02:00:07 +0200424:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson90c58022010-03-03 01:55:09 +0000425including argument descriptions.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000426
Benjamin Peterson90c58022010-03-03 01:55:09 +0000427The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
Georg Brandld2decd92010-03-02 22:17:38 +0000428will add information about the default value of each of the arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000429
430 >>> parser = argparse.ArgumentParser(
431 ... prog='PROG',
432 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
433 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
434 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
435 >>> parser.print_help()
436 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
437
438 positional arguments:
439 bar BAR! (default: [1, 2, 3])
440
441 optional arguments:
442 -h, --help show this help message and exit
443 --foo FOO FOO! (default: 42)
444
445
446conflict_handler
447^^^^^^^^^^^^^^^^
448
Benjamin Peterson90c58022010-03-03 01:55:09 +0000449:class:`ArgumentParser` objects do not allow two actions with the same option
450string. By default, :class:`ArgumentParser` objects raises an exception if an
451attempt is made to create an argument with an option string that is already in
452use::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000453
454 >>> parser = argparse.ArgumentParser(prog='PROG')
455 >>> parser.add_argument('-f', '--foo', help='old foo help')
456 >>> parser.add_argument('--foo', help='new foo help')
457 Traceback (most recent call last):
458 ..
459 ArgumentError: argument --foo: conflicting option string(s): --foo
460
461Sometimes (e.g. when using parents_) it may be useful to simply override any
Georg Brandld2decd92010-03-02 22:17:38 +0000462older arguments with the same option string. To get this behavior, the value
Benjamin Petersona39e9662010-03-02 22:05:59 +0000463``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson90c58022010-03-03 01:55:09 +0000464:class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000465
466 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
467 >>> parser.add_argument('-f', '--foo', help='old foo help')
468 >>> parser.add_argument('--foo', help='new foo help')
469 >>> parser.print_help()
470 usage: PROG [-h] [-f FOO] [--foo FOO]
471
472 optional arguments:
473 -h, --help show this help message and exit
474 -f FOO old foo help
475 --foo FOO new foo help
476
Benjamin Peterson90c58022010-03-03 01:55:09 +0000477Note that :class:`ArgumentParser` objects only remove an action if all of its
478option strings are overridden. So, in the example above, the old ``-f/--foo``
479action is retained as the ``-f`` action, because only the ``--foo`` option
480string was overridden.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000481
482
483prog
484^^^^
485
Benjamin Peterson90c58022010-03-03 01:55:09 +0000486By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
487how to display the name of the program in help messages. This default is almost
Ezio Melotti019551f2010-05-19 00:32:52 +0000488always desirable because it will make the help messages match how the program was
Benjamin Peterson90c58022010-03-03 01:55:09 +0000489invoked on the command line. For example, consider a file named
490``myprogram.py`` with the following code::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000491
492 import argparse
493 parser = argparse.ArgumentParser()
494 parser.add_argument('--foo', help='foo help')
495 args = parser.parse_args()
496
497The help for this program will display ``myprogram.py`` as the program name
498(regardless of where the program was invoked from)::
499
500 $ python myprogram.py --help
501 usage: myprogram.py [-h] [--foo FOO]
502
503 optional arguments:
504 -h, --help show this help message and exit
505 --foo FOO foo help
506 $ cd ..
507 $ python subdir\myprogram.py --help
508 usage: myprogram.py [-h] [--foo FOO]
509
510 optional arguments:
511 -h, --help show this help message and exit
512 --foo FOO foo help
513
514To change this default behavior, another value can be supplied using the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000515``prog=`` argument to :class:`ArgumentParser`::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000516
517 >>> parser = argparse.ArgumentParser(prog='myprogram')
518 >>> parser.print_help()
519 usage: myprogram [-h]
520
521 optional arguments:
522 -h, --help show this help message and exit
523
524Note that the program name, whether determined from ``sys.argv[0]`` or from the
525``prog=`` argument, is available to help messages using the ``%(prog)s`` format
526specifier.
527
528::
529
530 >>> parser = argparse.ArgumentParser(prog='myprogram')
531 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
532 >>> parser.print_help()
533 usage: myprogram [-h] [--foo FOO]
534
535 optional arguments:
536 -h, --help show this help message and exit
537 --foo FOO foo of the myprogram program
538
539
540usage
541^^^^^
542
Benjamin Peterson90c58022010-03-03 01:55:09 +0000543By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Petersona39e9662010-03-02 22:05:59 +0000544arguments it contains::
545
546 >>> parser = argparse.ArgumentParser(prog='PROG')
547 >>> parser.add_argument('--foo', nargs='?', help='foo help')
548 >>> parser.add_argument('bar', nargs='+', help='bar help')
549 >>> parser.print_help()
550 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
551
552 positional arguments:
553 bar bar help
554
555 optional arguments:
556 -h, --help show this help message and exit
557 --foo [FOO] foo help
558
Benjamin Peterson90c58022010-03-03 01:55:09 +0000559The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000560
561 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
562 >>> parser.add_argument('--foo', nargs='?', help='foo help')
563 >>> parser.add_argument('bar', nargs='+', help='bar help')
564 >>> parser.print_help()
565 usage: PROG [options]
566
567 positional arguments:
568 bar bar help
569
570 optional arguments:
571 -h, --help show this help message and exit
572 --foo [FOO] foo help
573
Benjamin Peterson90c58022010-03-03 01:55:09 +0000574The ``%(prog)s`` format specifier is available to fill in the program name in
575your usage messages.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000576
577
578The add_argument() method
579-------------------------
580
Éric Araujobb42f5e2012-02-20 02:08:01 +0100581.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
582 [const], [default], [type], [choices], [required], \
583 [help], [metavar], [dest])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000584
Ezio Melotti12125822011-04-16 23:04:51 +0300585 Define how a single command-line argument should be parsed. Each parameter
Benjamin Petersona39e9662010-03-02 22:05:59 +0000586 has its own more detailed description below, but in short they are:
587
588 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottid281f142011-04-21 23:09:27 +0300589 or ``-f, --foo``.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000590
591 * action_ - The basic type of action to be taken when this argument is
Ezio Melotti12125822011-04-16 23:04:51 +0300592 encountered at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000593
594 * nargs_ - The number of command-line arguments that should be consumed.
595
596 * const_ - A constant value required by some action_ and nargs_ selections.
597
598 * default_ - The value produced if the argument is absent from the
Ezio Melotti12125822011-04-16 23:04:51 +0300599 command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000600
Ezio Melotti12125822011-04-16 23:04:51 +0300601 * type_ - The type to which the command-line argument should be converted.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000602
603 * choices_ - A container of the allowable values for the argument.
604
605 * required_ - Whether or not the command-line option may be omitted
606 (optionals only).
607
608 * help_ - A brief description of what the argument does.
609
610 * metavar_ - A name for the argument in usage messages.
611
612 * dest_ - The name of the attribute to be added to the object returned by
613 :meth:`parse_args`.
614
Benjamin Peterson90c58022010-03-03 01:55:09 +0000615The following sections describe how each of these are used.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000616
Georg Brandlb8d0e362010-11-26 07:53:50 +0000617
Benjamin Petersona39e9662010-03-02 22:05:59 +0000618name or flags
619^^^^^^^^^^^^^
620
Ezio Melottic69313a2011-04-22 01:29:13 +0300621The :meth:`~ArgumentParser.add_argument` method must know whether an optional
622argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
623filenames, is expected. The first arguments passed to
624:meth:`~ArgumentParser.add_argument` must therefore be either a series of
625flags, or a simple argument name. For example, an optional argument could
626be created like::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000627
628 >>> parser.add_argument('-f', '--foo')
629
630while a positional argument could be created like::
631
632 >>> parser.add_argument('bar')
633
Ezio Melottic69313a2011-04-22 01:29:13 +0300634When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
635identified by the ``-`` prefix, and the remaining arguments will be assumed to
636be positional::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000637
638 >>> parser = argparse.ArgumentParser(prog='PROG')
639 >>> parser.add_argument('-f', '--foo')
640 >>> parser.add_argument('bar')
641 >>> parser.parse_args(['BAR'])
642 Namespace(bar='BAR', foo=None)
643 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
644 Namespace(bar='BAR', foo='FOO')
645 >>> parser.parse_args(['--foo', 'FOO'])
646 usage: PROG [-h] [-f FOO] bar
647 PROG: error: too few arguments
648
Georg Brandlb8d0e362010-11-26 07:53:50 +0000649
Benjamin Petersona39e9662010-03-02 22:05:59 +0000650action
651^^^^^^
652
Éric Araujo67719bd2011-08-19 02:00:07 +0200653:class:`ArgumentParser` objects associate command-line arguments with actions. These
654actions can do just about anything with the command-line arguments associated with
Benjamin Petersona39e9662010-03-02 22:05:59 +0000655them, though most actions simply add an attribute to the object returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300656:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Éric Araujo67719bd2011-08-19 02:00:07 +0200657how the command-line arguments should be handled. The supported actions are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000658
Georg Brandld2decd92010-03-02 22:17:38 +0000659* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti310619c2011-04-21 23:06:48 +0300660 action. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000661
662 >>> parser = argparse.ArgumentParser()
663 >>> parser.add_argument('--foo')
664 >>> parser.parse_args('--foo 1'.split())
665 Namespace(foo='1')
666
667* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti310619c2011-04-21 23:06:48 +0300668 argument. (Note that the const_ keyword argument defaults to the rather
669 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
670 optional arguments that specify some sort of flag. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000671
672 >>> parser = argparse.ArgumentParser()
673 >>> parser.add_argument('--foo', action='store_const', const=42)
674 >>> parser.parse_args('--foo'.split())
675 Namespace(foo=42)
676
Raymond Hettinger421467f2011-11-20 11:05:23 -0800677* ``'store_true'`` and ``'store_false'`` - These are special cases of
678 ``'store_const'`` using for storing the values ``True`` and ``False``
679 respectively. In addition, they create default values of *False* and *True*
680 respectively. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000681
682 >>> parser = argparse.ArgumentParser()
683 >>> parser.add_argument('--foo', action='store_true')
684 >>> parser.add_argument('--bar', action='store_false')
Raymond Hettinger421467f2011-11-20 11:05:23 -0800685 >>> parser.add_argument('--baz', action='store_false')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000686 >>> parser.parse_args('--foo --bar'.split())
Raymond Hettinger421467f2011-11-20 11:05:23 -0800687 Namespace(bar=False, baz=True, foo=True)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000688
689* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson90c58022010-03-03 01:55:09 +0000690 list. This is useful to allow an option to be specified multiple times.
691 Example usage::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000692
693 >>> parser = argparse.ArgumentParser()
694 >>> parser.add_argument('--foo', action='append')
695 >>> parser.parse_args('--foo 1 --foo 2'.split())
696 Namespace(foo=['1', '2'])
697
698* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson90c58022010-03-03 01:55:09 +0000699 the const_ keyword argument to the list. (Note that the const_ keyword
700 argument defaults to ``None``.) The ``'append_const'`` action is typically
701 useful when multiple arguments need to store constants to the same list. For
702 example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000703
704 >>> parser = argparse.ArgumentParser()
705 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
706 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
707 >>> parser.parse_args('--str --int'.split())
708 Namespace(types=[<type 'str'>, <type 'int'>])
709
Sandro Tosi8b211fc2012-01-04 23:24:48 +0100710* ``'count'`` - This counts the number of times a keyword argument occurs. For
711 example, this is useful for increasing verbosity levels::
712
713 >>> parser = argparse.ArgumentParser()
714 >>> parser.add_argument('--verbose', '-v', action='count')
715 >>> parser.parse_args('-vvv'.split())
716 Namespace(verbose=3)
717
718* ``'help'`` - This prints a complete help message for all the options in the
719 current parser and then exits. By default a help action is automatically
720 added to the parser. See :class:`ArgumentParser` for details of how the
721 output is created.
722
Benjamin Petersona39e9662010-03-02 22:05:59 +0000723* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melottic69313a2011-04-22 01:29:13 +0300724 :meth:`~ArgumentParser.add_argument` call, and prints version information
Éric Araujobb42f5e2012-02-20 02:08:01 +0100725 and exits when invoked::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000726
727 >>> import argparse
728 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard74bd9cf2010-05-24 02:38:00 +0000729 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
730 >>> parser.parse_args(['--version'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000731 PROG 2.0
732
733You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson90c58022010-03-03 01:55:09 +0000734the Action API. The easiest way to do this is to extend
735:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
736``__call__`` method should accept four parameters:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000737
738* ``parser`` - The ArgumentParser object which contains this action.
739
Éric Araujof0d44bc2011-07-29 17:59:17 +0200740* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melottic69313a2011-04-22 01:29:13 +0300741 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
742 object.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000743
Éric Araujo67719bd2011-08-19 02:00:07 +0200744* ``values`` - The associated command-line arguments, with any type conversions
745 applied. (Type conversions are specified with the type_ keyword argument to
Ezio Melottic69313a2011-04-22 01:29:13 +0300746 :meth:`~ArgumentParser.add_argument`.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000747
748* ``option_string`` - The option string that was used to invoke this action.
749 The ``option_string`` argument is optional, and will be absent if the action
750 is associated with a positional argument.
751
Benjamin Peterson90c58022010-03-03 01:55:09 +0000752An example of a custom action::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000753
754 >>> class FooAction(argparse.Action):
755 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl8891e232010-08-01 21:23:50 +0000756 ... print '%r %r %r' % (namespace, values, option_string)
757 ... setattr(namespace, self.dest, values)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000758 ...
759 >>> parser = argparse.ArgumentParser()
760 >>> parser.add_argument('--foo', action=FooAction)
761 >>> parser.add_argument('bar', action=FooAction)
762 >>> args = parser.parse_args('1 --foo 2'.split())
763 Namespace(bar=None, foo=None) '1' None
764 Namespace(bar='1', foo=None) '2' '--foo'
765 >>> args
766 Namespace(bar='1', foo='2')
767
768
769nargs
770^^^^^
771
772ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson90c58022010-03-03 01:55:09 +0000773single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti0a43ecc2011-04-21 22:56:51 +0300774different number of command-line arguments with a single action. The supported
Benjamin Peterson90c58022010-03-03 01:55:09 +0000775values are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000776
Éric Araujobb42f5e2012-02-20 02:08:01 +0100777* ``N`` (an integer). ``N`` arguments from the command line will be gathered
778 together into a list. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000779
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000780 >>> parser = argparse.ArgumentParser()
781 >>> parser.add_argument('--foo', nargs=2)
782 >>> parser.add_argument('bar', nargs=1)
783 >>> parser.parse_args('c --foo a b'.split())
784 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000785
Georg Brandl35e7a8f2010-10-06 10:41:31 +0000786 Note that ``nargs=1`` produces a list of one item. This is different from
787 the default, in which the item is produced by itself.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000788
Éric Araujo67719bd2011-08-19 02:00:07 +0200789* ``'?'``. One argument will be consumed from the command line if possible, and
790 produced as a single item. If no command-line argument is present, the value from
Benjamin Petersona39e9662010-03-02 22:05:59 +0000791 default_ will be produced. Note that for optional arguments, there is an
792 additional case - the option string is present but not followed by a
Éric Araujo67719bd2011-08-19 02:00:07 +0200793 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Petersona39e9662010-03-02 22:05:59 +0000794 examples to illustrate this::
795
Georg Brandld2decd92010-03-02 22:17:38 +0000796 >>> parser = argparse.ArgumentParser()
797 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
798 >>> parser.add_argument('bar', nargs='?', default='d')
799 >>> parser.parse_args('XX --foo YY'.split())
800 Namespace(bar='XX', foo='YY')
801 >>> parser.parse_args('XX --foo'.split())
802 Namespace(bar='XX', foo='c')
803 >>> parser.parse_args(''.split())
804 Namespace(bar='d', foo='d')
Benjamin Petersona39e9662010-03-02 22:05:59 +0000805
Georg Brandld2decd92010-03-02 22:17:38 +0000806 One of the more common uses of ``nargs='?'`` is to allow optional input and
807 output files::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000808
Georg Brandld2decd92010-03-02 22:17:38 +0000809 >>> parser = argparse.ArgumentParser()
Georg Brandlb8d0e362010-11-26 07:53:50 +0000810 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
811 ... default=sys.stdin)
812 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
813 ... default=sys.stdout)
Georg Brandld2decd92010-03-02 22:17:38 +0000814 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl585bbb92011-01-09 09:33:09 +0000815 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
816 outfile=<open file 'output.txt', mode 'w' at 0x...>)
Georg Brandld2decd92010-03-02 22:17:38 +0000817 >>> parser.parse_args([])
Georg Brandl585bbb92011-01-09 09:33:09 +0000818 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
819 outfile=<open file '<stdout>', mode 'w' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +0000820
Éric Araujo67719bd2011-08-19 02:00:07 +0200821* ``'*'``. All command-line arguments present are gathered into a list. Note that
Georg Brandld2decd92010-03-02 22:17:38 +0000822 it generally doesn't make much sense to have more than one positional argument
823 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
824 possible. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000825
Georg Brandld2decd92010-03-02 22:17:38 +0000826 >>> parser = argparse.ArgumentParser()
827 >>> parser.add_argument('--foo', nargs='*')
828 >>> parser.add_argument('--bar', nargs='*')
829 >>> parser.add_argument('baz', nargs='*')
830 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
831 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
Benjamin Petersona39e9662010-03-02 22:05:59 +0000832
833* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
834 list. Additionally, an error message will be generated if there wasn't at
Éric Araujo67719bd2011-08-19 02:00:07 +0200835 least one command-line argument present. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000836
Georg Brandld2decd92010-03-02 22:17:38 +0000837 >>> parser = argparse.ArgumentParser(prog='PROG')
838 >>> parser.add_argument('foo', nargs='+')
839 >>> parser.parse_args('a b'.split())
840 Namespace(foo=['a', 'b'])
841 >>> parser.parse_args(''.split())
842 usage: PROG [-h] foo [foo ...]
843 PROG: error: too few arguments
Benjamin Petersona39e9662010-03-02 22:05:59 +0000844
Sandro Tosicb212272012-01-19 22:22:35 +0100845* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
846 into a list. This is commonly useful for command line utilities that dispatch
Éric Araujobb42f5e2012-02-20 02:08:01 +0100847 to other command line utilities::
Sandro Tosi10f047d2012-01-19 21:59:34 +0100848
849 >>> parser = argparse.ArgumentParser(prog='PROG')
850 >>> parser.add_argument('--foo')
851 >>> parser.add_argument('command')
852 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosicb212272012-01-19 22:22:35 +0100853 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
854 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi10f047d2012-01-19 21:59:34 +0100855
Éric Araujo67719bd2011-08-19 02:00:07 +0200856If the ``nargs`` keyword argument is not provided, the number of arguments consumed
857is determined by the action_. Generally this means a single command-line argument
Benjamin Petersona39e9662010-03-02 22:05:59 +0000858will be consumed and a single item (not a list) will be produced.
859
860
861const
862^^^^^
863
Ezio Melottic69313a2011-04-22 01:29:13 +0300864The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
865constant values that are not read from the command line but are required for
866the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Petersona39e9662010-03-02 22:05:59 +0000867
Ezio Melottic69313a2011-04-22 01:29:13 +0300868* When :meth:`~ArgumentParser.add_argument` is called with
869 ``action='store_const'`` or ``action='append_const'``. These actions add the
Éric Araujobb42f5e2012-02-20 02:08:01 +0100870 ``const`` value to one of the attributes of the object returned by
871 :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000872
Ezio Melottic69313a2011-04-22 01:29:13 +0300873* When :meth:`~ArgumentParser.add_argument` is called with option strings
874 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujo67719bd2011-08-19 02:00:07 +0200875 argument that can be followed by zero or one command-line arguments.
Ezio Melottic69313a2011-04-22 01:29:13 +0300876 When parsing the command line, if the option string is encountered with no
Éric Araujo67719bd2011-08-19 02:00:07 +0200877 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melottic69313a2011-04-22 01:29:13 +0300878 See the nargs_ description for examples.
Benjamin Petersona39e9662010-03-02 22:05:59 +0000879
880The ``const`` keyword argument defaults to ``None``.
881
882
883default
884^^^^^^^
885
886All optional arguments and some positional arguments may be omitted at the
Ezio Melottic69313a2011-04-22 01:29:13 +0300887command line. The ``default`` keyword argument of
888:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujo67719bd2011-08-19 02:00:07 +0200889specifies what value should be used if the command-line argument is not present.
Ezio Melottic69313a2011-04-22 01:29:13 +0300890For optional arguments, the ``default`` value is used when the option string
891was not present at the command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000892
893 >>> parser = argparse.ArgumentParser()
894 >>> parser.add_argument('--foo', default=42)
895 >>> parser.parse_args('--foo 2'.split())
896 Namespace(foo='2')
897 >>> parser.parse_args(''.split())
898 Namespace(foo=42)
899
Éric Araujo67719bd2011-08-19 02:00:07 +0200900For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
901is used when no command-line argument was present::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000902
903 >>> parser = argparse.ArgumentParser()
904 >>> parser.add_argument('foo', nargs='?', default=42)
905 >>> parser.parse_args('a'.split())
906 Namespace(foo='a')
907 >>> parser.parse_args(''.split())
908 Namespace(foo=42)
909
910
Benjamin Peterson90c58022010-03-03 01:55:09 +0000911Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
912command-line argument was not present.::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000913
914 >>> parser = argparse.ArgumentParser()
915 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
916 >>> parser.parse_args([])
917 Namespace()
918 >>> parser.parse_args(['--foo', '1'])
919 Namespace(foo='1')
920
921
922type
923^^^^
924
Éric Araujo67719bd2011-08-19 02:00:07 +0200925By default, :class:`ArgumentParser` objects read command-line arguments in as simple
926strings. However, quite often the command-line string should instead be
927interpreted as another type, like a :class:`float` or :class:`int`. The
Ezio Melottic69313a2011-04-22 01:29:13 +0300928``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujo67719bd2011-08-19 02:00:07 +0200929necessary type-checking and type conversions to be performed. Common built-in
930types and functions can be used directly as the value of the ``type`` argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000931
932 >>> parser = argparse.ArgumentParser()
933 >>> parser.add_argument('foo', type=int)
934 >>> parser.add_argument('bar', type=file)
935 >>> parser.parse_args('2 temp.txt'.split())
936 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
937
938To ease the use of various types of files, the argparse module provides the
939factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandld2decd92010-03-02 22:17:38 +0000940``file`` object. For example, ``FileType('w')`` can be used to create a
Benjamin Petersona39e9662010-03-02 22:05:59 +0000941writable file::
942
943 >>> parser = argparse.ArgumentParser()
944 >>> parser.add_argument('bar', type=argparse.FileType('w'))
945 >>> parser.parse_args(['out.txt'])
946 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
947
Benjamin Peterson90c58022010-03-03 01:55:09 +0000948``type=`` can take any callable that takes a single string argument and returns
Éric Araujo67719bd2011-08-19 02:00:07 +0200949the converted value::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000950
951 >>> def perfect_square(string):
952 ... value = int(string)
953 ... sqrt = math.sqrt(value)
954 ... if sqrt != int(sqrt):
955 ... msg = "%r is not a perfect square" % string
956 ... raise argparse.ArgumentTypeError(msg)
957 ... return value
958 ...
959 >>> parser = argparse.ArgumentParser(prog='PROG')
960 >>> parser.add_argument('foo', type=perfect_square)
961 >>> parser.parse_args('9'.split())
962 Namespace(foo=9)
963 >>> parser.parse_args('7'.split())
964 usage: PROG [-h] foo
965 PROG: error: argument foo: '7' is not a perfect square
966
Benjamin Peterson90c58022010-03-03 01:55:09 +0000967The choices_ keyword argument may be more convenient for type checkers that
968simply check against a range of values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000969
970 >>> parser = argparse.ArgumentParser(prog='PROG')
971 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
972 >>> parser.parse_args('7'.split())
973 Namespace(foo=7)
974 >>> parser.parse_args('11'.split())
975 usage: PROG [-h] {5,6,7,8,9}
976 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
977
978See the choices_ section for more details.
979
980
981choices
982^^^^^^^
983
Éric Araujo67719bd2011-08-19 02:00:07 +0200984Some command-line arguments should be selected from a restricted set of values.
Benjamin Peterson90c58022010-03-03 01:55:09 +0000985These can be handled by passing a container object as the ``choices`` keyword
Ezio Melottic69313a2011-04-22 01:29:13 +0300986argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Éric Araujo67719bd2011-08-19 02:00:07 +0200987parsed, argument values will be checked, and an error message will be displayed if
988the argument was not one of the acceptable values::
Benjamin Petersona39e9662010-03-02 22:05:59 +0000989
990 >>> parser = argparse.ArgumentParser(prog='PROG')
991 >>> parser.add_argument('foo', choices='abc')
992 >>> parser.parse_args('c'.split())
993 Namespace(foo='c')
994 >>> parser.parse_args('X'.split())
995 usage: PROG [-h] {a,b,c}
996 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
997
998Note that inclusion in the ``choices`` container is checked after any type_
999conversions have been performed, so the type of the objects in the ``choices``
1000container should match the type_ specified::
1001
1002 >>> parser = argparse.ArgumentParser(prog='PROG')
1003 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
1004 >>> parser.parse_args('1j'.split())
1005 Namespace(foo=1j)
1006 >>> parser.parse_args('-- -4'.split())
1007 usage: PROG [-h] {1,1j}
1008 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
1009
1010Any object that supports the ``in`` operator can be passed as the ``choices``
Georg Brandld2decd92010-03-02 22:17:38 +00001011value, so :class:`dict` objects, :class:`set` objects, custom containers,
1012etc. are all supported.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001013
1014
1015required
1016^^^^^^^^
1017
Ezio Melotti01b600c2011-04-21 16:12:17 +03001018In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Ezio Melotti12125822011-04-16 23:04:51 +03001019indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001020To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melottic69313a2011-04-22 01:29:13 +03001021keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001022
1023 >>> parser = argparse.ArgumentParser()
1024 >>> parser.add_argument('--foo', required=True)
1025 >>> parser.parse_args(['--foo', 'BAR'])
1026 Namespace(foo='BAR')
1027 >>> parser.parse_args([])
1028 usage: argparse.py [-h] [--foo FOO]
1029 argparse.py: error: option --foo is required
1030
Ezio Melottic69313a2011-04-22 01:29:13 +03001031As the example shows, if an option is marked as ``required``,
1032:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1033present at the command line.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001034
Benjamin Peterson90c58022010-03-03 01:55:09 +00001035.. note::
1036
1037 Required options are generally considered bad form because users expect
1038 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001039
1040
1041help
1042^^^^
1043
Benjamin Peterson90c58022010-03-03 01:55:09 +00001044The ``help`` value is a string containing a brief description of the argument.
1045When a user requests help (usually by using ``-h`` or ``--help`` at the
Ezio Melotti12125822011-04-16 23:04:51 +03001046command line), these ``help`` descriptions will be displayed with each
Georg Brandld2decd92010-03-02 22:17:38 +00001047argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001048
1049 >>> parser = argparse.ArgumentParser(prog='frobble')
1050 >>> parser.add_argument('--foo', action='store_true',
1051 ... help='foo the bars before frobbling')
1052 >>> parser.add_argument('bar', nargs='+',
1053 ... help='one of the bars to be frobbled')
1054 >>> parser.parse_args('-h'.split())
1055 usage: frobble [-h] [--foo] bar [bar ...]
1056
1057 positional arguments:
1058 bar one of the bars to be frobbled
1059
1060 optional arguments:
1061 -h, --help show this help message and exit
1062 --foo foo the bars before frobbling
1063
1064The ``help`` strings can include various format specifiers to avoid repetition
1065of things like the program name or the argument default_. The available
1066specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melottic69313a2011-04-22 01:29:13 +03001067:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001068
1069 >>> parser = argparse.ArgumentParser(prog='frobble')
1070 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1071 ... help='the bar to %(prog)s (default: %(default)s)')
1072 >>> parser.print_help()
1073 usage: frobble [-h] [bar]
1074
1075 positional arguments:
1076 bar the bar to frobble (default: 42)
1077
1078 optional arguments:
1079 -h, --help show this help message and exit
1080
Sandro Tosi711f5472012-01-03 18:31:51 +01001081:mod:`argparse` supports silencing the help entry for certain options, by
1082setting the ``help`` value to ``argparse.SUPPRESS``::
1083
1084 >>> parser = argparse.ArgumentParser(prog='frobble')
1085 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1086 >>> parser.print_help()
1087 usage: frobble [-h]
1088
1089 optional arguments:
1090 -h, --help show this help message and exit
1091
Benjamin Petersona39e9662010-03-02 22:05:59 +00001092
1093metavar
1094^^^^^^^
1095
Benjamin Peterson90c58022010-03-03 01:55:09 +00001096When :class:`ArgumentParser` generates help messages, it need some way to refer
Georg Brandld2decd92010-03-02 22:17:38 +00001097to each expected argument. By default, ArgumentParser objects use the dest_
Benjamin Petersona39e9662010-03-02 22:05:59 +00001098value as the "name" of each object. By default, for positional argument
1099actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson90c58022010-03-03 01:55:09 +00001100the dest_ value is uppercased. So, a single positional argument with
Eli Benderskybba1dd52011-11-11 16:42:11 +02001101``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujo67719bd2011-08-19 02:00:07 +02001102optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson90c58022010-03-03 01:55:09 +00001103will be referred to as ``FOO``. An example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001104
1105 >>> parser = argparse.ArgumentParser()
1106 >>> parser.add_argument('--foo')
1107 >>> parser.add_argument('bar')
1108 >>> parser.parse_args('X --foo Y'.split())
1109 Namespace(bar='X', foo='Y')
1110 >>> parser.print_help()
1111 usage: [-h] [--foo FOO] bar
1112
1113 positional arguments:
1114 bar
1115
1116 optional arguments:
1117 -h, --help show this help message and exit
1118 --foo FOO
1119
Benjamin Peterson90c58022010-03-03 01:55:09 +00001120An alternative name can be specified with ``metavar``::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001121
1122 >>> parser = argparse.ArgumentParser()
1123 >>> parser.add_argument('--foo', metavar='YYY')
1124 >>> parser.add_argument('bar', metavar='XXX')
1125 >>> parser.parse_args('X --foo Y'.split())
1126 Namespace(bar='X', foo='Y')
1127 >>> parser.print_help()
1128 usage: [-h] [--foo YYY] XXX
1129
1130 positional arguments:
1131 XXX
1132
1133 optional arguments:
1134 -h, --help show this help message and exit
1135 --foo YYY
1136
1137Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001138attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1139by the dest_ value.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001140
1141Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001142Providing a tuple to ``metavar`` specifies a different display for each of the
1143arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001144
1145 >>> parser = argparse.ArgumentParser(prog='PROG')
1146 >>> parser.add_argument('-x', nargs=2)
1147 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1148 >>> parser.print_help()
1149 usage: PROG [-h] [-x X X] [--foo bar baz]
1150
1151 optional arguments:
1152 -h, --help show this help message and exit
1153 -x X X
1154 --foo bar baz
1155
1156
1157dest
1158^^^^
1159
Benjamin Peterson90c58022010-03-03 01:55:09 +00001160Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melottic69313a2011-04-22 01:29:13 +03001161object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1162attribute is determined by the ``dest`` keyword argument of
1163:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1164``dest`` is normally supplied as the first argument to
1165:meth:`~ArgumentParser.add_argument`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001166
1167 >>> parser = argparse.ArgumentParser()
1168 >>> parser.add_argument('bar')
1169 >>> parser.parse_args('XXX'.split())
1170 Namespace(bar='XXX')
1171
1172For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson90c58022010-03-03 01:55:09 +00001173the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo67719bd2011-08-19 02:00:07 +02001174taking the first long option string and stripping away the initial ``--``
Benjamin Petersona39e9662010-03-02 22:05:59 +00001175string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo67719bd2011-08-19 02:00:07 +02001176the first short option string by stripping the initial ``-`` character. Any
1177internal ``-`` characters will be converted to ``_`` characters to make sure
Georg Brandld2decd92010-03-02 22:17:38 +00001178the string is a valid attribute name. The examples below illustrate this
Benjamin Petersona39e9662010-03-02 22:05:59 +00001179behavior::
1180
1181 >>> parser = argparse.ArgumentParser()
1182 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1183 >>> parser.add_argument('-x', '-y')
1184 >>> parser.parse_args('-f 1 -x 2'.split())
1185 Namespace(foo_bar='1', x='2')
1186 >>> parser.parse_args('--foo 1 -y 2'.split())
1187 Namespace(foo_bar='1', x='2')
1188
Benjamin Peterson90c58022010-03-03 01:55:09 +00001189``dest`` allows a custom attribute name to be provided::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001190
1191 >>> parser = argparse.ArgumentParser()
1192 >>> parser.add_argument('--foo', dest='bar')
1193 >>> parser.parse_args('--foo XXX'.split())
1194 Namespace(bar='XXX')
1195
1196
1197The parse_args() method
1198-----------------------
1199
Georg Brandlb8d0e362010-11-26 07:53:50 +00001200.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001201
Benjamin Peterson90c58022010-03-03 01:55:09 +00001202 Convert argument strings to objects and assign them as attributes of the
Georg Brandld2decd92010-03-02 22:17:38 +00001203 namespace. Return the populated namespace.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001204
1205 Previous calls to :meth:`add_argument` determine exactly what objects are
1206 created and how they are assigned. See the documentation for
1207 :meth:`add_argument` for details.
1208
Éric Araujo67719bd2011-08-19 02:00:07 +02001209 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson90c58022010-03-03 01:55:09 +00001210 :class:`Namespace` object is created for the attributes.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001211
Georg Brandlb8d0e362010-11-26 07:53:50 +00001212
Benjamin Petersona39e9662010-03-02 22:05:59 +00001213Option value syntax
1214^^^^^^^^^^^^^^^^^^^
1215
Ezio Melottic69313a2011-04-22 01:29:13 +03001216The :meth:`~ArgumentParser.parse_args` method supports several ways of
1217specifying the value of an option (if it takes one). In the simplest case, the
1218option and its value are passed as two separate arguments::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001219
1220 >>> parser = argparse.ArgumentParser(prog='PROG')
1221 >>> parser.add_argument('-x')
1222 >>> parser.add_argument('--foo')
1223 >>> parser.parse_args('-x X'.split())
1224 Namespace(foo=None, x='X')
1225 >>> parser.parse_args('--foo FOO'.split())
1226 Namespace(foo='FOO', x=None)
1227
Benjamin Peterson90c58022010-03-03 01:55:09 +00001228For long options (options with names longer than a single character), the option
Ezio Melotti12125822011-04-16 23:04:51 +03001229and value can also be passed as a single command-line argument, using ``=`` to
Georg Brandld2decd92010-03-02 22:17:38 +00001230separate them::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001231
1232 >>> parser.parse_args('--foo=FOO'.split())
1233 Namespace(foo='FOO', x=None)
1234
Benjamin Peterson90c58022010-03-03 01:55:09 +00001235For short options (options only one character long), the option and its value
1236can be concatenated::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001237
1238 >>> parser.parse_args('-xX'.split())
1239 Namespace(foo=None, x='X')
1240
Benjamin Peterson90c58022010-03-03 01:55:09 +00001241Several short options can be joined together, using only a single ``-`` prefix,
1242as long as only the last option (or none of them) requires a value::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001243
1244 >>> parser = argparse.ArgumentParser(prog='PROG')
1245 >>> parser.add_argument('-x', action='store_true')
1246 >>> parser.add_argument('-y', action='store_true')
1247 >>> parser.add_argument('-z')
1248 >>> parser.parse_args('-xyzZ'.split())
1249 Namespace(x=True, y=True, z='Z')
1250
1251
1252Invalid arguments
1253^^^^^^^^^^^^^^^^^
1254
Ezio Melottic69313a2011-04-22 01:29:13 +03001255While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1256variety of errors, including ambiguous options, invalid types, invalid options,
1257wrong number of positional arguments, etc. When it encounters such an error,
1258it exits and prints the error along with a usage message::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001259
1260 >>> parser = argparse.ArgumentParser(prog='PROG')
1261 >>> parser.add_argument('--foo', type=int)
1262 >>> parser.add_argument('bar', nargs='?')
1263
1264 >>> # invalid type
1265 >>> parser.parse_args(['--foo', 'spam'])
1266 usage: PROG [-h] [--foo FOO] [bar]
1267 PROG: error: argument --foo: invalid int value: 'spam'
1268
1269 >>> # invalid option
1270 >>> parser.parse_args(['--bar'])
1271 usage: PROG [-h] [--foo FOO] [bar]
1272 PROG: error: no such option: --bar
1273
1274 >>> # wrong number of arguments
1275 >>> parser.parse_args(['spam', 'badger'])
1276 usage: PROG [-h] [--foo FOO] [bar]
1277 PROG: error: extra arguments found: badger
1278
1279
Éric Araujo67719bd2011-08-19 02:00:07 +02001280Arguments containing ``-``
1281^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Petersona39e9662010-03-02 22:05:59 +00001282
Ezio Melottic69313a2011-04-22 01:29:13 +03001283The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1284the user has clearly made a mistake, but some situations are inherently
Éric Araujo67719bd2011-08-19 02:00:07 +02001285ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melottic69313a2011-04-22 01:29:13 +03001286attempt to specify an option or an attempt to provide a positional argument.
1287The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo67719bd2011-08-19 02:00:07 +02001288arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melottic69313a2011-04-22 01:29:13 +03001289there are no options in the parser that look like negative numbers::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001290
1291 >>> parser = argparse.ArgumentParser(prog='PROG')
1292 >>> parser.add_argument('-x')
1293 >>> parser.add_argument('foo', nargs='?')
1294
1295 >>> # no negative number options, so -1 is a positional argument
1296 >>> parser.parse_args(['-x', '-1'])
1297 Namespace(foo=None, x='-1')
1298
1299 >>> # no negative number options, so -1 and -5 are positional arguments
1300 >>> parser.parse_args(['-x', '-1', '-5'])
1301 Namespace(foo='-5', x='-1')
1302
1303 >>> parser = argparse.ArgumentParser(prog='PROG')
1304 >>> parser.add_argument('-1', dest='one')
1305 >>> parser.add_argument('foo', nargs='?')
1306
1307 >>> # negative number options present, so -1 is an option
1308 >>> parser.parse_args(['-1', 'X'])
1309 Namespace(foo=None, one='X')
1310
1311 >>> # negative number options present, so -2 is an option
1312 >>> parser.parse_args(['-2'])
1313 usage: PROG [-h] [-1 ONE] [foo]
1314 PROG: error: no such option: -2
1315
1316 >>> # negative number options present, so both -1s are options
1317 >>> parser.parse_args(['-1', '-1'])
1318 usage: PROG [-h] [-1 ONE] [foo]
1319 PROG: error: argument -1: expected one argument
1320
Éric Araujo67719bd2011-08-19 02:00:07 +02001321If you have positional arguments that must begin with ``-`` and don't look
Benjamin Petersona39e9662010-03-02 22:05:59 +00001322like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melottic69313a2011-04-22 01:29:13 +03001323:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1324argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001325
1326 >>> parser.parse_args(['--', '-f'])
1327 Namespace(foo='-f', one=None)
1328
1329
1330Argument abbreviations
1331^^^^^^^^^^^^^^^^^^^^^^
1332
Ezio Melottic69313a2011-04-22 01:29:13 +03001333The :meth:`~ArgumentParser.parse_args` method allows long options to be
1334abbreviated if the abbreviation is unambiguous::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001335
1336 >>> parser = argparse.ArgumentParser(prog='PROG')
1337 >>> parser.add_argument('-bacon')
1338 >>> parser.add_argument('-badger')
1339 >>> parser.parse_args('-bac MMM'.split())
1340 Namespace(bacon='MMM', badger=None)
1341 >>> parser.parse_args('-bad WOOD'.split())
1342 Namespace(bacon=None, badger='WOOD')
1343 >>> parser.parse_args('-ba BA'.split())
1344 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1345 PROG: error: ambiguous option: -ba could match -badger, -bacon
1346
Benjamin Peterson90c58022010-03-03 01:55:09 +00001347An error is produced for arguments that could produce more than one options.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001348
1349
1350Beyond ``sys.argv``
1351^^^^^^^^^^^^^^^^^^^
1352
Éric Araujo67719bd2011-08-19 02:00:07 +02001353Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Georg Brandld2decd92010-03-02 22:17:38 +00001354of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melottic69313a2011-04-22 01:29:13 +03001355:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1356interactive prompt::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001357
1358 >>> parser = argparse.ArgumentParser()
1359 >>> parser.add_argument(
1360 ... 'integers', metavar='int', type=int, choices=xrange(10),
1361 ... nargs='+', help='an integer in the range 0..9')
1362 >>> parser.add_argument(
1363 ... '--sum', dest='accumulate', action='store_const', const=sum,
1364 ... default=max, help='sum the integers (default: find the max)')
1365 >>> parser.parse_args(['1', '2', '3', '4'])
1366 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1367 >>> parser.parse_args('1 2 3 4 --sum'.split())
1368 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1369
1370
Steven Bethard3f69a052011-03-26 19:59:02 +01001371The Namespace object
1372^^^^^^^^^^^^^^^^^^^^
1373
Éric Araujof0d44bc2011-07-29 17:59:17 +02001374.. class:: Namespace
1375
1376 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1377 an object holding attributes and return it.
1378
1379This class is deliberately simple, just an :class:`object` subclass with a
1380readable string representation. If you prefer to have dict-like view of the
1381attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethard3f69a052011-03-26 19:59:02 +01001382
1383 >>> parser = argparse.ArgumentParser()
1384 >>> parser.add_argument('--foo')
1385 >>> args = parser.parse_args(['--foo', 'BAR'])
1386 >>> vars(args)
1387 {'foo': 'BAR'}
Benjamin Petersona39e9662010-03-02 22:05:59 +00001388
Benjamin Peterson90c58022010-03-03 01:55:09 +00001389It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethard3f69a052011-03-26 19:59:02 +01001390already existing object, rather than a new :class:`Namespace` object. This can
1391be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001392
1393 >>> class C(object):
1394 ... pass
1395 ...
1396 >>> c = C()
1397 >>> parser = argparse.ArgumentParser()
1398 >>> parser.add_argument('--foo')
1399 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1400 >>> c.foo
1401 'BAR'
1402
1403
1404Other utilities
1405---------------
1406
1407Sub-commands
1408^^^^^^^^^^^^
1409
Benjamin Peterson90c58022010-03-03 01:55:09 +00001410.. method:: ArgumentParser.add_subparsers()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001411
Benjamin Peterson90c58022010-03-03 01:55:09 +00001412 Many programs split up their functionality into a number of sub-commands,
Georg Brandld2decd92010-03-02 22:17:38 +00001413 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson90c58022010-03-03 01:55:09 +00001414 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Georg Brandld2decd92010-03-02 22:17:38 +00001415 this way can be a particularly good idea when a program performs several
1416 different functions which require different kinds of command-line arguments.
Benjamin Peterson90c58022010-03-03 01:55:09 +00001417 :class:`ArgumentParser` supports the creation of such sub-commands with the
Georg Brandld2decd92010-03-02 22:17:38 +00001418 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1419 called with no arguments and returns an special action object. This object
Ezio Melottic69313a2011-04-22 01:29:13 +03001420 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1421 command name and any :class:`ArgumentParser` constructor arguments, and
1422 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001423
1424 Some example usage::
1425
1426 >>> # create the top-level parser
1427 >>> parser = argparse.ArgumentParser(prog='PROG')
1428 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1429 >>> subparsers = parser.add_subparsers(help='sub-command help')
1430 >>>
1431 >>> # create the parser for the "a" command
1432 >>> parser_a = subparsers.add_parser('a', help='a help')
1433 >>> parser_a.add_argument('bar', type=int, help='bar help')
1434 >>>
1435 >>> # create the parser for the "b" command
1436 >>> parser_b = subparsers.add_parser('b', help='b help')
1437 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1438 >>>
Éric Araujo67719bd2011-08-19 02:00:07 +02001439 >>> # parse some argument lists
Benjamin Petersona39e9662010-03-02 22:05:59 +00001440 >>> parser.parse_args(['a', '12'])
1441 Namespace(bar=12, foo=False)
1442 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1443 Namespace(baz='Z', foo=True)
1444
1445 Note that the object returned by :meth:`parse_args` will only contain
1446 attributes for the main parser and the subparser that was selected by the
1447 command line (and not any other subparsers). So in the example above, when
Éric Araujo67719bd2011-08-19 02:00:07 +02001448 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1449 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Petersona39e9662010-03-02 22:05:59 +00001450 ``baz`` attributes are present.
1451
1452 Similarly, when a help message is requested from a subparser, only the help
Georg Brandld2decd92010-03-02 22:17:38 +00001453 for that particular parser will be printed. The help message will not
Benjamin Peterson90c58022010-03-03 01:55:09 +00001454 include parent parser or sibling parser messages. (A help message for each
1455 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001456 to :meth:`add_parser` as above.)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001457
1458 ::
1459
1460 >>> parser.parse_args(['--help'])
1461 usage: PROG [-h] [--foo] {a,b} ...
1462
1463 positional arguments:
1464 {a,b} sub-command help
1465 a a help
1466 b b help
1467
1468 optional arguments:
1469 -h, --help show this help message and exit
1470 --foo foo help
1471
1472 >>> parser.parse_args(['a', '--help'])
1473 usage: PROG a [-h] bar
1474
1475 positional arguments:
1476 bar bar help
1477
1478 optional arguments:
1479 -h, --help show this help message and exit
1480
1481 >>> parser.parse_args(['b', '--help'])
1482 usage: PROG b [-h] [--baz {X,Y,Z}]
1483
1484 optional arguments:
1485 -h, --help show this help message and exit
1486 --baz {X,Y,Z} baz help
1487
Georg Brandld2decd92010-03-02 22:17:38 +00001488 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1489 keyword arguments. When either is present, the subparser's commands will
1490 appear in their own group in the help output. For example::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001491
1492 >>> parser = argparse.ArgumentParser()
1493 >>> subparsers = parser.add_subparsers(title='subcommands',
1494 ... description='valid subcommands',
1495 ... help='additional help')
1496 >>> subparsers.add_parser('foo')
1497 >>> subparsers.add_parser('bar')
1498 >>> parser.parse_args(['-h'])
1499 usage: [-h] {foo,bar} ...
1500
1501 optional arguments:
1502 -h, --help show this help message and exit
1503
1504 subcommands:
1505 valid subcommands
1506
1507 {foo,bar} additional help
1508
1509
Georg Brandld2decd92010-03-02 22:17:38 +00001510 One particularly effective way of handling sub-commands is to combine the use
1511 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1512 that each subparser knows which Python function it should execute. For
Benjamin Petersona39e9662010-03-02 22:05:59 +00001513 example::
1514
1515 >>> # sub-command functions
1516 >>> def foo(args):
1517 ... print args.x * args.y
1518 ...
1519 >>> def bar(args):
1520 ... print '((%s))' % args.z
1521 ...
1522 >>> # create the top-level parser
1523 >>> parser = argparse.ArgumentParser()
1524 >>> subparsers = parser.add_subparsers()
1525 >>>
1526 >>> # create the parser for the "foo" command
1527 >>> parser_foo = subparsers.add_parser('foo')
1528 >>> parser_foo.add_argument('-x', type=int, default=1)
1529 >>> parser_foo.add_argument('y', type=float)
1530 >>> parser_foo.set_defaults(func=foo)
1531 >>>
1532 >>> # create the parser for the "bar" command
1533 >>> parser_bar = subparsers.add_parser('bar')
1534 >>> parser_bar.add_argument('z')
1535 >>> parser_bar.set_defaults(func=bar)
1536 >>>
1537 >>> # parse the args and call whatever function was selected
1538 >>> args = parser.parse_args('foo 1 -x 2'.split())
1539 >>> args.func(args)
1540 2.0
1541 >>>
1542 >>> # parse the args and call whatever function was selected
1543 >>> args = parser.parse_args('bar XYZYX'.split())
1544 >>> args.func(args)
1545 ((XYZYX))
1546
Éric Araujobb42f5e2012-02-20 02:08:01 +01001547 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson90c58022010-03-03 01:55:09 +00001548 appropriate function after argument parsing is complete. Associating
1549 functions with actions like this is typically the easiest way to handle the
1550 different actions for each of your subparsers. However, if it is necessary
1551 to check the name of the subparser that was invoked, the ``dest`` keyword
1552 argument to the :meth:`add_subparsers` call will work::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001553
1554 >>> parser = argparse.ArgumentParser()
1555 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1556 >>> subparser1 = subparsers.add_parser('1')
1557 >>> subparser1.add_argument('-x')
1558 >>> subparser2 = subparsers.add_parser('2')
1559 >>> subparser2.add_argument('y')
1560 >>> parser.parse_args(['2', 'frobble'])
1561 Namespace(subparser_name='2', y='frobble')
1562
1563
1564FileType objects
1565^^^^^^^^^^^^^^^^
1566
1567.. class:: FileType(mode='r', bufsize=None)
1568
1569 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson90c58022010-03-03 01:55:09 +00001570 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujo67719bd2011-08-19 02:00:07 +02001571 :class:`FileType` objects as their type will open command-line arguments as files
Éric Araujobb42f5e2012-02-20 02:08:01 +01001572 with the requested modes and buffer sizes::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001573
Éric Araujobb42f5e2012-02-20 02:08:01 +01001574 >>> parser = argparse.ArgumentParser()
1575 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1576 >>> parser.parse_args(['--output', 'out'])
1577 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001578
1579 FileType objects understand the pseudo-argument ``'-'`` and automatically
1580 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
Éric Araujobb42f5e2012-02-20 02:08:01 +01001581 ``sys.stdout`` for writable :class:`FileType` objects::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001582
Éric Araujobb42f5e2012-02-20 02:08:01 +01001583 >>> parser = argparse.ArgumentParser()
1584 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1585 >>> parser.parse_args(['-'])
1586 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001587
1588
1589Argument groups
1590^^^^^^^^^^^^^^^
1591
Georg Brandlb8d0e362010-11-26 07:53:50 +00001592.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001593
Benjamin Peterson90c58022010-03-03 01:55:09 +00001594 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Petersona39e9662010-03-02 22:05:59 +00001595 "positional arguments" and "optional arguments" when displaying help
1596 messages. When there is a better conceptual grouping of arguments than this
1597 default one, appropriate groups can be created using the
1598 :meth:`add_argument_group` method::
1599
1600 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1601 >>> group = parser.add_argument_group('group')
1602 >>> group.add_argument('--foo', help='foo help')
1603 >>> group.add_argument('bar', help='bar help')
1604 >>> parser.print_help()
1605 usage: PROG [--foo FOO] bar
1606
1607 group:
1608 bar bar help
1609 --foo FOO foo help
1610
1611 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson90c58022010-03-03 01:55:09 +00001612 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1613 :class:`ArgumentParser`. When an argument is added to the group, the parser
1614 treats it just like a normal argument, but displays the argument in a
1615 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandlb8d0e362010-11-26 07:53:50 +00001616 accepts *title* and *description* arguments which can be used to
Benjamin Peterson90c58022010-03-03 01:55:09 +00001617 customize this display::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001618
1619 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1620 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1621 >>> group1.add_argument('foo', help='foo help')
1622 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1623 >>> group2.add_argument('--bar', help='bar help')
1624 >>> parser.print_help()
1625 usage: PROG [--bar BAR] foo
1626
1627 group1:
1628 group1 description
1629
1630 foo foo help
1631
1632 group2:
1633 group2 description
1634
1635 --bar BAR bar help
1636
Sandro Tosi48a88952012-03-26 19:35:52 +02001637 Note that any arguments not in your user-defined groups will end up back
1638 in the usual "positional arguments" and "optional arguments" sections.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001639
1640
1641Mutual exclusion
1642^^^^^^^^^^^^^^^^
1643
Georg Brandlb8d0e362010-11-26 07:53:50 +00001644.. method:: add_mutually_exclusive_group(required=False)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001645
Ezio Melotti01b600c2011-04-21 16:12:17 +03001646 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1647 one of the arguments in the mutually exclusive group was present on the
1648 command line::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001649
1650 >>> parser = argparse.ArgumentParser(prog='PROG')
1651 >>> group = parser.add_mutually_exclusive_group()
1652 >>> group.add_argument('--foo', action='store_true')
1653 >>> group.add_argument('--bar', action='store_false')
1654 >>> parser.parse_args(['--foo'])
1655 Namespace(bar=True, foo=True)
1656 >>> parser.parse_args(['--bar'])
1657 Namespace(bar=False, foo=False)
1658 >>> parser.parse_args(['--foo', '--bar'])
1659 usage: PROG [-h] [--foo | --bar]
1660 PROG: error: argument --bar: not allowed with argument --foo
1661
Georg Brandlb8d0e362010-11-26 07:53:50 +00001662 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001663 argument, to indicate that at least one of the mutually exclusive arguments
1664 is required::
1665
1666 >>> parser = argparse.ArgumentParser(prog='PROG')
1667 >>> group = parser.add_mutually_exclusive_group(required=True)
1668 >>> group.add_argument('--foo', action='store_true')
1669 >>> group.add_argument('--bar', action='store_false')
1670 >>> parser.parse_args([])
1671 usage: PROG [-h] (--foo | --bar)
1672 PROG: error: one of the arguments --foo --bar is required
1673
1674 Note that currently mutually exclusive argument groups do not support the
Ezio Melottic69313a2011-04-22 01:29:13 +03001675 *title* and *description* arguments of
1676 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001677
1678
1679Parser defaults
1680^^^^^^^^^^^^^^^
1681
Benjamin Peterson90c58022010-03-03 01:55:09 +00001682.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001683
Georg Brandld2decd92010-03-02 22:17:38 +00001684 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujo67719bd2011-08-19 02:00:07 +02001685 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melottic69313a2011-04-22 01:29:13 +03001686 actions. :meth:`set_defaults` allows some additional
Ezio Melotti12125822011-04-16 23:04:51 +03001687 attributes that are determined without any inspection of the command line to
Benjamin Petersonc516d192010-03-03 02:04:24 +00001688 be added::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001689
1690 >>> parser = argparse.ArgumentParser()
1691 >>> parser.add_argument('foo', type=int)
1692 >>> parser.set_defaults(bar=42, baz='badger')
1693 >>> parser.parse_args(['736'])
1694 Namespace(bar=42, baz='badger', foo=736)
1695
Benjamin Peterson90c58022010-03-03 01:55:09 +00001696 Note that parser-level defaults always override argument-level defaults::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001697
1698 >>> parser = argparse.ArgumentParser()
1699 >>> parser.add_argument('--foo', default='bar')
1700 >>> parser.set_defaults(foo='spam')
1701 >>> parser.parse_args([])
1702 Namespace(foo='spam')
1703
Benjamin Peterson90c58022010-03-03 01:55:09 +00001704 Parser-level defaults can be particularly useful when working with multiple
1705 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1706 example of this type.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001707
Benjamin Peterson90c58022010-03-03 01:55:09 +00001708.. method:: ArgumentParser.get_default(dest)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001709
1710 Get the default value for a namespace attribute, as set by either
Benjamin Peterson90c58022010-03-03 01:55:09 +00001711 :meth:`~ArgumentParser.add_argument` or by
1712 :meth:`~ArgumentParser.set_defaults`::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001713
1714 >>> parser = argparse.ArgumentParser()
1715 >>> parser.add_argument('--foo', default='badger')
1716 >>> parser.get_default('foo')
1717 'badger'
1718
1719
1720Printing help
1721^^^^^^^^^^^^^
1722
Ezio Melottic69313a2011-04-22 01:29:13 +03001723In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1724care of formatting and printing any usage or error messages. However, several
1725formatting methods are available:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001726
Georg Brandlb8d0e362010-11-26 07:53:50 +00001727.. method:: ArgumentParser.print_usage(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001728
1729 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray561b96f2011-02-11 17:25:54 +00001730 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Petersona39e9662010-03-02 22:05:59 +00001731 assumed.
1732
Georg Brandlb8d0e362010-11-26 07:53:50 +00001733.. method:: ArgumentParser.print_help(file=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001734
1735 Print a help message, including the program usage and information about the
Georg Brandlb8d0e362010-11-26 07:53:50 +00001736 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray561b96f2011-02-11 17:25:54 +00001737 ``None``, :data:`sys.stdout` is assumed.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001738
1739There are also variants of these methods that simply return a string instead of
1740printing it:
1741
Georg Brandlb8d0e362010-11-26 07:53:50 +00001742.. method:: ArgumentParser.format_usage()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001743
1744 Return a string containing a brief description of how the
1745 :class:`ArgumentParser` should be invoked on the command line.
1746
Georg Brandlb8d0e362010-11-26 07:53:50 +00001747.. method:: ArgumentParser.format_help()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001748
1749 Return a string containing a help message, including the program usage and
1750 information about the arguments registered with the :class:`ArgumentParser`.
1751
1752
Benjamin Petersona39e9662010-03-02 22:05:59 +00001753Partial parsing
1754^^^^^^^^^^^^^^^
1755
Georg Brandlb8d0e362010-11-26 07:53:50 +00001756.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001757
Ezio Melotti12125822011-04-16 23:04:51 +03001758Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Petersona39e9662010-03-02 22:05:59 +00001759the remaining arguments on to another script or program. In these cases, the
Ezio Melottic69313a2011-04-22 01:29:13 +03001760:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson90c58022010-03-03 01:55:09 +00001761:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1762extra arguments are present. Instead, it returns a two item tuple containing
1763the populated namespace and the list of remaining argument strings.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001764
1765::
1766
1767 >>> parser = argparse.ArgumentParser()
1768 >>> parser.add_argument('--foo', action='store_true')
1769 >>> parser.add_argument('bar')
1770 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1771 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1772
1773
1774Customizing file parsing
1775^^^^^^^^^^^^^^^^^^^^^^^^
1776
Benjamin Peterson90c58022010-03-03 01:55:09 +00001777.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Petersona39e9662010-03-02 22:05:59 +00001778
Georg Brandlb8d0e362010-11-26 07:53:50 +00001779 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Petersona39e9662010-03-02 22:05:59 +00001780 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson90c58022010-03-03 01:55:09 +00001781 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1782 fancier reading.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001783
Georg Brandlb8d0e362010-11-26 07:53:50 +00001784 This method takes a single argument *arg_line* which is a string read from
Benjamin Petersona39e9662010-03-02 22:05:59 +00001785 the argument file. It returns a list of arguments parsed from this string.
1786 The method is called once per line read from the argument file, in order.
1787
Georg Brandld2decd92010-03-02 22:17:38 +00001788 A useful override of this method is one that treats each space-separated word
1789 as an argument::
Benjamin Petersona39e9662010-03-02 22:05:59 +00001790
1791 def convert_arg_line_to_args(self, arg_line):
1792 for arg in arg_line.split():
1793 if not arg.strip():
1794 continue
1795 yield arg
1796
1797
Georg Brandlb8d0e362010-11-26 07:53:50 +00001798Exiting methods
1799^^^^^^^^^^^^^^^
1800
1801.. method:: ArgumentParser.exit(status=0, message=None)
1802
1803 This method terminates the program, exiting with the specified *status*
1804 and, if given, it prints a *message* before that.
1805
1806.. method:: ArgumentParser.error(message)
1807
1808 This method prints a usage message including the *message* to the
Senthil Kumaranc1ee4ef2011-08-03 07:43:52 +08001809 standard error and terminates the program with a status code of 2.
Georg Brandlb8d0e362010-11-26 07:53:50 +00001810
1811
Georg Brandl58df6792010-07-03 10:25:47 +00001812.. _argparse-from-optparse:
1813
Benjamin Petersona39e9662010-03-02 22:05:59 +00001814Upgrading optparse code
1815-----------------------
1816
Ezio Melottic69313a2011-04-22 01:29:13 +03001817Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti01b600c2011-04-21 16:12:17 +03001818with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1819transparently, particularly with the changes required to support the new
1820``nargs=`` specifiers and better usage messages. When most everything in
1821:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1822longer seemed practical to try to maintain the backwards compatibility.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001823
Ezio Melotti01b600c2011-04-21 16:12:17 +03001824A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Petersona39e9662010-03-02 22:05:59 +00001825
Ezio Melottic69313a2011-04-22 01:29:13 +03001826* Replace all :meth:`optparse.OptionParser.add_option` calls with
1827 :meth:`ArgumentParser.add_argument` calls.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001828
R David Murray5080cad2012-03-30 18:09:07 -04001829* Replace ``(options, args) = parser.parse_args()`` with ``args =
Georg Brandl585bbb92011-01-09 09:33:09 +00001830 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
R David Murray5080cad2012-03-30 18:09:07 -04001831 calls for the positional arguments. Keep in mind that what was previously
1832 called ``options``, now in :mod:`argparse` context is called ``args``.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001833
1834* Replace callback actions and the ``callback_*`` keyword arguments with
1835 ``type`` or ``action`` arguments.
1836
1837* Replace string names for ``type`` keyword arguments with the corresponding
1838 type objects (e.g. int, float, complex, etc).
1839
Benjamin Peterson90c58022010-03-03 01:55:09 +00001840* Replace :class:`optparse.Values` with :class:`Namespace` and
1841 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1842 :exc:`ArgumentError`.
Benjamin Petersona39e9662010-03-02 22:05:59 +00001843
Georg Brandld2decd92010-03-02 22:17:38 +00001844* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotti2eab88e2011-04-21 15:26:46 +03001845 the standard Python syntax to use dictionaries to format strings, that is,
Georg Brandld2decd92010-03-02 22:17:38 +00001846 ``%(default)s`` and ``%(prog)s``.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00001847
1848* Replace the OptionParser constructor ``version`` argument with a call to
1849 ``parser.add_argument('--version', action='version', version='<the version>')``