blob: 2617ae5aa4641a6c9abbf28e6d1a374b24668414 [file] [log] [blame]
Georg Brandl69518bc2011-04-16 16:44:54 +02001:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
Georg Brandle0bf91d2010-10-17 10:34:28 +00002===============================================================================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4.. module:: argparse
Éric Araujod9d7bca2011-08-10 04:19:03 +02005 :synopsis: Command-line option and argument parsing library.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00006.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
Benjamin Peterson698a18a2010-03-02 22:34:37 +00007.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
8
Raymond Hettingera1993682011-01-27 01:20:32 +00009.. versionadded:: 3.2
10
Éric Araujo19f9b712011-08-19 00:49:18 +020011**Source code:** :source:`Lib/argparse.py`
12
Raymond Hettingera1993682011-01-27 01:20:32 +000013--------------
Benjamin Peterson698a18a2010-03-02 22:34:37 +000014
Ezio Melotti2409d772011-04-16 23:13:50 +030015The :mod:`argparse` module makes it easy to write user-friendly command-line
Benjamin Peterson98047eb2010-03-03 02:07:08 +000016interfaces. The program defines what arguments it requires, and :mod:`argparse`
Benjamin Peterson698a18a2010-03-02 22:34:37 +000017will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
Benjamin Peterson98047eb2010-03-03 02:07:08 +000018module also automatically generates help and usage messages and issues errors
19when users give the program invalid arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000020
Georg Brandle0bf91d2010-10-17 10:34:28 +000021
Benjamin Peterson698a18a2010-03-02 22:34:37 +000022Example
23-------
24
Benjamin Peterson98047eb2010-03-03 02:07:08 +000025The following code is a Python program that takes a list of integers and
26produces either the sum or the max::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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()
Benjamin Petersonb2deb112010-03-03 02:09:18 +000038 print(args.accumulate(args.integers))
Benjamin Peterson698a18a2010-03-02 22:34:37 +000039
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 Brandle0bf91d2010-10-17 10:34:28 +000072
Benjamin Peterson698a18a2010-03-02 22:34:37 +000073Creating a parser
74^^^^^^^^^^^^^^^^^
75
Benjamin Peterson2614cda2010-03-21 22:36:19 +000076The first step in using the :mod:`argparse` is creating an
Benjamin Peterson98047eb2010-03-03 02:07:08 +000077:class:`ArgumentParser` object::
Benjamin Peterson698a18a2010-03-02 22:34:37 +000078
79 >>> parser = argparse.ArgumentParser(description='Process some integers.')
80
81The :class:`ArgumentParser` object will hold all the information necessary to
Ezio Melotticca4ef82011-04-21 15:26:46 +030082parse the command line into Python data types.
Benjamin Peterson698a18a2010-03-02 22:34:37 +000083
84
85Adding arguments
86^^^^^^^^^^^^^^^^
87
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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 Melotti5569e9b2011-04-22 01:42:10 +0300100Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
Benjamin Peterson698a18a2010-03-02 22:34:37 +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.
105
Georg Brandle0bf91d2010-10-17 10:34:28 +0000106
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000107Parsing arguments
108^^^^^^^^^^^^^^^^^
109
Éric Araujod9d7bca2011-08-10 04:19:03 +0200110:class:`ArgumentParser` parses arguments through the
Georg Brandl69518bc2011-04-16 16:44:54 +0200111:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Éric Araujofde92422011-08-19 01:30:26 +0200112convert each argument to the appropriate type and then invoke the appropriate action.
Éric Araujo63b18a42011-07-29 17:59:17 +0200113In most cases, this means a simple :class:`Namespace` object will be built up from
Georg Brandl69518bc2011-04-16 16:44:54 +0200114attributes parsed out of the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000115
116 >>> parser.parse_args(['--sum', '7', '-1', '42'])
117 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
118
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000119In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
120arguments, and the :class:`ArgumentParser` will automatically determine the
Éric Araujod9d7bca2011-08-10 04:19:03 +0200121command-line arguments from :data:`sys.argv`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000122
123
124ArgumentParser objects
125----------------------
126
Georg Brandlc9007082011-01-09 09:04:08 +0000127.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
128 [argument_default], [parents], [prefix_chars], \
129 [conflict_handler], [formatter_class])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000130
131 Create a new :class:`ArgumentParser` object. Each parameter has its own more
132 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 Peterson98047eb2010-03-03 02:07:08 +0000138 * add_help_ - Add a -h/--help option to the parser. (default: ``True``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000139
140 * argument_default_ - Set the global default value for arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000141 (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000142
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000143 * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000150 which additional arguments should be read. (default: ``None``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000157 * prog_ - The name of the program (default:
Éric Araujo37b5f9e2011-09-01 03:19:30 +0200158 ``sys.argv[0]``)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000159
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000160 * usage_ - The string describing the program usage (default: generated)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000161
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000162The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000163
164
165description
166^^^^^^^^^^^
167
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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
184given space. To change this behavior, see the formatter_class_ argument.
185
186
187epilog
188^^^^^^
189
190Some programs like to display additional description of the program after the
191description of the arguments. Such text can be specified using the ``epilog=``
192argument to :class:`ArgumentParser`::
193
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 Peterson98047eb2010-03-03 02:07:08 +0000209argument to :class:`ArgumentParser`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000210
211
212add_help
213^^^^^^^^
214
R. David Murray88c49fe2010-08-03 17:56:09 +0000215By default, ArgumentParser objects add an option which simply displays
216the parser's help message. For example, consider a file named
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
Georg Brandl884843d2011-04-16 17:02:58 +0200224If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +0000236:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Murray88c49fe2010-08-03 17:56:09 +0000246The help option is typically ``-h/--help``. The exception to this is
Éric Araujo543edbd2011-08-19 01:45:12 +0200247if the ``prefix_chars=`` is specified and does not include ``-``, in
R. David Murray88c49fe2010-08-03 17:56:09 +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 Peterson698a18a2010-03-02 22:34:37 +0000260prefix_chars
261^^^^^^^^^^^^
262
Éric Araujo543edbd2011-08-19 01:45:12 +0200263Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
R. David Murray88c49fe2010-08-03 17:56:09 +0000264Parsers that need to support different or additional prefix
265characters, e.g. for options
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Araujo543edbd2011-08-19 01:45:12 +0200276characters that does not include ``-`` will cause ``-f/--foo`` options to be
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000277disallowed.
278
279
280fromfile_prefix_chars
281^^^^^^^^^^^^^^^^^^^^^
282
Benjamin Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +0000289
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000290 >>> with open('args.txt', 'w') as fp:
291 ... fp.write('-f\nbar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Melotti5569e9b2011-04-22 01:42:10 +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 Peterson698a18a2010-03-02 22:34:37 +0000302
303The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
304arguments will never be treated as file references.
305
Georg Brandle0bf91d2010-10-17 10:34:28 +0000306
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000307argument_default
308^^^^^^^^^^^^^^^^
309
310Generally, argument defaults are specified either by passing a default to
Ezio Melotti5569e9b2011-04-22 01:42:10 +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 Peterson98047eb2010-03-03 02:07:08 +0000317calls, we supply ``argument_default=SUPPRESS``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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 Peterson98047eb2010-03-03 02:07:08 +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 Peterson698a18a2010-03-02 22:34:37 +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
351Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000352:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
353and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000354
Steven Bethardd186f992011-03-26 21:49:00 +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 Peterson698a18a2010-03-02 22:34:37 +0000360
361formatter_class
362^^^^^^^^^^^^^^^
363
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000364:class:`ArgumentParser` objects allow the help formatting to be customized by
Ezio Melotti707d1e62011-04-22 01:57:47 +0300365specifying an alternate formatting class. Currently, there are four such
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300366classes:
367
368.. class:: RawDescriptionHelpFormatter
369 RawTextHelpFormatter
370 ArgumentDefaultsHelpFormatter
Ezio Melotti707d1e62011-04-22 01:57:47 +0300371 MetavarTypeHelpFormatter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000372
Steven Bethard0331e902011-03-26 14:48:04 +0100373:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
374more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000375By default, :class:`ArgumentParser` objects line-wrap the description_ and
376epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
Steven Bethard0331e902011-03-26 14:48:04 +0100398Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000399indicates that description_ and epilog_ are already correctly formatted and
400should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
Steven Bethard0331e902011-03-26 14:48:04 +0100424:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000425including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000426
Steven Bethard0331e902011-03-26 14:48:04 +0100427:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
428default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +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
Steven Bethard0331e902011-03-26 14:48:04 +0100445:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
Ezio Melottif1064492011-10-19 11:06:26 +0300446argument as the display name for its values (rather than using the dest_
Steven Bethard0331e902011-03-26 14:48:04 +0100447as the regular formatter does)::
448
449 >>> parser = argparse.ArgumentParser(
450 ... prog='PROG',
451 ... formatter_class=argparse.MetavarTypeHelpFormatter)
452 >>> parser.add_argument('--foo', type=int)
453 >>> parser.add_argument('bar', type=float)
454 >>> parser.print_help()
455 usage: PROG [-h] [--foo int] float
456
457 positional arguments:
458 float
459
460 optional arguments:
461 -h, --help show this help message and exit
462 --foo int
463
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000464
465conflict_handler
466^^^^^^^^^^^^^^^^
467
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000468:class:`ArgumentParser` objects do not allow two actions with the same option
469string. By default, :class:`ArgumentParser` objects raises an exception if an
470attempt is made to create an argument with an option string that is already in
471use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000472
473 >>> parser = argparse.ArgumentParser(prog='PROG')
474 >>> parser.add_argument('-f', '--foo', help='old foo help')
475 >>> parser.add_argument('--foo', help='new foo help')
476 Traceback (most recent call last):
477 ..
478 ArgumentError: argument --foo: conflicting option string(s): --foo
479
480Sometimes (e.g. when using parents_) it may be useful to simply override any
481older arguments with the same option string. To get this behavior, the value
482``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000483:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000484
485 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
486 >>> parser.add_argument('-f', '--foo', help='old foo help')
487 >>> parser.add_argument('--foo', help='new foo help')
488 >>> parser.print_help()
489 usage: PROG [-h] [-f FOO] [--foo FOO]
490
491 optional arguments:
492 -h, --help show this help message and exit
493 -f FOO old foo help
494 --foo FOO new foo help
495
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000496Note that :class:`ArgumentParser` objects only remove an action if all of its
497option strings are overridden. So, in the example above, the old ``-f/--foo``
498action is retained as the ``-f`` action, because only the ``--foo`` option
499string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000500
501
502prog
503^^^^
504
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000505By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
506how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000507always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000508invoked on the command line. For example, consider a file named
509``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000510
511 import argparse
512 parser = argparse.ArgumentParser()
513 parser.add_argument('--foo', help='foo help')
514 args = parser.parse_args()
515
516The help for this program will display ``myprogram.py`` as the program name
517(regardless of where the program was invoked from)::
518
519 $ python myprogram.py --help
520 usage: myprogram.py [-h] [--foo FOO]
521
522 optional arguments:
523 -h, --help show this help message and exit
524 --foo FOO foo help
525 $ cd ..
526 $ python subdir\myprogram.py --help
527 usage: myprogram.py [-h] [--foo FOO]
528
529 optional arguments:
530 -h, --help show this help message and exit
531 --foo FOO foo help
532
533To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000534``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000535
536 >>> parser = argparse.ArgumentParser(prog='myprogram')
537 >>> parser.print_help()
538 usage: myprogram [-h]
539
540 optional arguments:
541 -h, --help show this help message and exit
542
543Note that the program name, whether determined from ``sys.argv[0]`` or from the
544``prog=`` argument, is available to help messages using the ``%(prog)s`` format
545specifier.
546
547::
548
549 >>> parser = argparse.ArgumentParser(prog='myprogram')
550 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
551 >>> parser.print_help()
552 usage: myprogram [-h] [--foo FOO]
553
554 optional arguments:
555 -h, --help show this help message and exit
556 --foo FOO foo of the myprogram program
557
558
559usage
560^^^^^
561
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000562By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000563arguments it contains::
564
565 >>> parser = argparse.ArgumentParser(prog='PROG')
566 >>> parser.add_argument('--foo', nargs='?', help='foo help')
567 >>> parser.add_argument('bar', nargs='+', help='bar help')
568 >>> parser.print_help()
569 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
570
571 positional arguments:
572 bar bar help
573
574 optional arguments:
575 -h, --help show this help message and exit
576 --foo [FOO] foo help
577
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000578The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000579
580 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
581 >>> parser.add_argument('--foo', nargs='?', help='foo help')
582 >>> parser.add_argument('bar', nargs='+', help='bar help')
583 >>> parser.print_help()
584 usage: PROG [options]
585
586 positional arguments:
587 bar bar help
588
589 optional arguments:
590 -h, --help show this help message and exit
591 --foo [FOO] foo help
592
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000593The ``%(prog)s`` format specifier is available to fill in the program name in
594your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000595
596
597The add_argument() method
598-------------------------
599
Georg Brandlc9007082011-01-09 09:04:08 +0000600.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
601 [const], [default], [type], [choices], [required], \
602 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000603
Georg Brandl69518bc2011-04-16 16:44:54 +0200604 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000605 has its own more detailed description below, but in short they are:
606
607 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
Ezio Melottidca309d2011-04-21 23:09:27 +0300608 or ``-f, --foo``.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000609
610 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200611 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000612
613 * nargs_ - The number of command-line arguments that should be consumed.
614
615 * const_ - A constant value required by some action_ and nargs_ selections.
616
617 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200618 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000619
Ezio Melotti2409d772011-04-16 23:13:50 +0300620 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000621
622 * choices_ - A container of the allowable values for the argument.
623
624 * required_ - Whether or not the command-line option may be omitted
625 (optionals only).
626
627 * help_ - A brief description of what the argument does.
628
629 * metavar_ - A name for the argument in usage messages.
630
631 * dest_ - The name of the attribute to be added to the object returned by
632 :meth:`parse_args`.
633
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000634The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000635
Georg Brandle0bf91d2010-10-17 10:34:28 +0000636
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000637name or flags
638^^^^^^^^^^^^^
639
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300640The :meth:`~ArgumentParser.add_argument` method must know whether an optional
641argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
642filenames, is expected. The first arguments passed to
643:meth:`~ArgumentParser.add_argument` must therefore be either a series of
644flags, or a simple argument name. For example, an optional argument could
645be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000646
647 >>> parser.add_argument('-f', '--foo')
648
649while a positional argument could be created like::
650
651 >>> parser.add_argument('bar')
652
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300653When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
654identified by the ``-`` prefix, and the remaining arguments will be assumed to
655be positional::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000656
657 >>> parser = argparse.ArgumentParser(prog='PROG')
658 >>> parser.add_argument('-f', '--foo')
659 >>> parser.add_argument('bar')
660 >>> parser.parse_args(['BAR'])
661 Namespace(bar='BAR', foo=None)
662 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
663 Namespace(bar='BAR', foo='FOO')
664 >>> parser.parse_args(['--foo', 'FOO'])
665 usage: PROG [-h] [-f FOO] bar
666 PROG: error: too few arguments
667
Georg Brandle0bf91d2010-10-17 10:34:28 +0000668
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000669action
670^^^^^^
671
Éric Araujod9d7bca2011-08-10 04:19:03 +0200672:class:`ArgumentParser` objects associate command-line arguments with actions. These
673actions can do just about anything with the command-line arguments associated with
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000674them, though most actions simply add an attribute to the object returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300675:meth:`~ArgumentParser.parse_args`. The ``action`` keyword argument specifies
Éric Araujod9d7bca2011-08-10 04:19:03 +0200676how the command-line arguments should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000677
678* ``'store'`` - This just stores the argument's value. This is the default
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300679 action. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000680
681 >>> parser = argparse.ArgumentParser()
682 >>> parser.add_argument('--foo')
683 >>> parser.parse_args('--foo 1'.split())
684 Namespace(foo='1')
685
686* ``'store_const'`` - This stores the value specified by the const_ keyword
Ezio Melotti2f1db7d2011-04-21 23:06:48 +0300687 argument. (Note that the const_ keyword argument defaults to the rather
688 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
689 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000690
691 >>> parser = argparse.ArgumentParser()
692 >>> parser.add_argument('--foo', action='store_const', const=42)
693 >>> parser.parse_args('--foo'.split())
694 Namespace(foo=42)
695
696* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000697 ``False`` respectively. These are special cases of ``'store_const'``. For
698 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000699
700 >>> parser = argparse.ArgumentParser()
701 >>> parser.add_argument('--foo', action='store_true')
702 >>> parser.add_argument('--bar', action='store_false')
703 >>> parser.parse_args('--foo --bar'.split())
704 Namespace(bar=False, foo=True)
705
706* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000707 list. This is useful to allow an option to be specified multiple times.
708 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000709
710 >>> parser = argparse.ArgumentParser()
711 >>> parser.add_argument('--foo', action='append')
712 >>> parser.parse_args('--foo 1 --foo 2'.split())
713 Namespace(foo=['1', '2'])
714
715* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000716 the const_ keyword argument to the list. (Note that the const_ keyword
717 argument defaults to ``None``.) The ``'append_const'`` action is typically
718 useful when multiple arguments need to store constants to the same list. For
719 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000720
721 >>> parser = argparse.ArgumentParser()
722 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
723 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
724 >>> parser.parse_args('--str --int'.split())
Florent Xicluna74e64952011-10-28 11:21:19 +0200725 Namespace(types=[<class 'str'>, <class 'int'>])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000726
Sandro Tosi98492a52012-01-04 23:25:04 +0100727* ``'count'`` - This counts the number of times a keyword argument occurs. For
728 example, this is useful for increasing verbosity levels::
729
730 >>> parser = argparse.ArgumentParser()
731 >>> parser.add_argument('--verbose', '-v', action='count')
732 >>> parser.parse_args('-vvv'.split())
733 Namespace(verbose=3)
734
735* ``'help'`` - This prints a complete help message for all the options in the
736 current parser and then exits. By default a help action is automatically
737 added to the parser. See :class:`ArgumentParser` for details of how the
738 output is created.
739
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000740* ``'version'`` - This expects a ``version=`` keyword argument in the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300741 :meth:`~ArgumentParser.add_argument` call, and prints version information
742 and exits when invoked.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000743
744 >>> import argparse
745 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000746 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
747 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000748 PROG 2.0
749
750You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000751the Action API. The easiest way to do this is to extend
752:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
753``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000754
755* ``parser`` - The ArgumentParser object which contains this action.
756
Éric Araujo63b18a42011-07-29 17:59:17 +0200757* ``namespace`` - The :class:`Namespace` object that will be returned by
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300758 :meth:`~ArgumentParser.parse_args`. Most actions add an attribute to this
759 object.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000760
Éric Araujod9d7bca2011-08-10 04:19:03 +0200761* ``values`` - The associated command-line arguments, with any type conversions
762 applied. (Type conversions are specified with the type_ keyword argument to
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300763 :meth:`~ArgumentParser.add_argument`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000764
765* ``option_string`` - The option string that was used to invoke this action.
766 The ``option_string`` argument is optional, and will be absent if the action
767 is associated with a positional argument.
768
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000769An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000770
771 >>> class FooAction(argparse.Action):
772 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000773 ... print('%r %r %r' % (namespace, values, option_string))
774 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000775 ...
776 >>> parser = argparse.ArgumentParser()
777 >>> parser.add_argument('--foo', action=FooAction)
778 >>> parser.add_argument('bar', action=FooAction)
779 >>> args = parser.parse_args('1 --foo 2'.split())
780 Namespace(bar=None, foo=None) '1' None
781 Namespace(bar='1', foo=None) '2' '--foo'
782 >>> args
783 Namespace(bar='1', foo='2')
784
785
786nargs
787^^^^^
788
789ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000790single action to be taken. The ``nargs`` keyword argument associates a
Ezio Melotti00f53af2011-04-21 22:56:51 +0300791different number of command-line arguments with a single action. The supported
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000792values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000793
Éric Araujo543edbd2011-08-19 01:45:12 +0200794* ``N`` (an integer). ``N`` arguments from the command line will be gathered together into a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000795 list. For example::
796
Georg Brandl682d7e02010-10-06 10:26:05 +0000797 >>> parser = argparse.ArgumentParser()
798 >>> parser.add_argument('--foo', nargs=2)
799 >>> parser.add_argument('bar', nargs=1)
800 >>> parser.parse_args('c --foo a b'.split())
801 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000802
Georg Brandl682d7e02010-10-06 10:26:05 +0000803 Note that ``nargs=1`` produces a list of one item. This is different from
804 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000805
Éric Araujofde92422011-08-19 01:30:26 +0200806* ``'?'``. One argument will be consumed from the command line if possible, and
807 produced as a single item. If no command-line argument is present, the value from
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000808 default_ will be produced. Note that for optional arguments, there is an
809 additional case - the option string is present but not followed by a
Éric Araujofde92422011-08-19 01:30:26 +0200810 command-line argument. In this case the value from const_ will be produced. Some
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000811 examples to illustrate this::
812
813 >>> parser = argparse.ArgumentParser()
814 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
815 >>> parser.add_argument('bar', nargs='?', default='d')
816 >>> parser.parse_args('XX --foo YY'.split())
817 Namespace(bar='XX', foo='YY')
818 >>> parser.parse_args('XX --foo'.split())
819 Namespace(bar='XX', foo='c')
820 >>> parser.parse_args(''.split())
821 Namespace(bar='d', foo='d')
822
823 One of the more common uses of ``nargs='?'`` is to allow optional input and
824 output files::
825
826 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000827 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
828 ... default=sys.stdin)
829 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
830 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000831 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000832 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
833 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000834 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000835 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
836 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000837
Éric Araujod9d7bca2011-08-10 04:19:03 +0200838* ``'*'``. All command-line arguments present are gathered into a list. Note that
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000839 it generally doesn't make much sense to have more than one positional argument
840 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
841 possible. For example::
842
843 >>> parser = argparse.ArgumentParser()
844 >>> parser.add_argument('--foo', nargs='*')
845 >>> parser.add_argument('--bar', nargs='*')
846 >>> parser.add_argument('baz', nargs='*')
847 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
848 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
849
850* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
851 list. Additionally, an error message will be generated if there wasn't at
Éric Araujofde92422011-08-19 01:30:26 +0200852 least one command-line argument present. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000853
854 >>> parser = argparse.ArgumentParser(prog='PROG')
855 >>> parser.add_argument('foo', nargs='+')
856 >>> parser.parse_args('a b'.split())
857 Namespace(foo=['a', 'b'])
858 >>> parser.parse_args(''.split())
859 usage: PROG [-h] foo [foo ...]
860 PROG: error: too few arguments
861
Sandro Tosida8e11a2012-01-19 22:23:00 +0100862* ``argparse.REMAINDER``. All the remaining command-line arguments are gathered
863 into a list. This is commonly useful for command line utilities that dispatch
864 to other command line utilities.
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100865
866 >>> parser = argparse.ArgumentParser(prog='PROG')
867 >>> parser.add_argument('--foo')
868 >>> parser.add_argument('command')
869 >>> parser.add_argument('args', nargs=argparse.REMAINDER)
Sandro Tosida8e11a2012-01-19 22:23:00 +0100870 >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
871 Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')
Sandro Tosi16bd0b42012-01-19 21:59:55 +0100872
Éric Araujod9d7bca2011-08-10 04:19:03 +0200873If the ``nargs`` keyword argument is not provided, the number of arguments consumed
Éric Araujofde92422011-08-19 01:30:26 +0200874is determined by the action_. Generally this means a single command-line argument
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000875will be consumed and a single item (not a list) will be produced.
876
877
878const
879^^^^^
880
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300881The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
882constant values that are not read from the command line but are required for
883the various :class:`ArgumentParser` actions. The two most common uses of it are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000884
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300885* When :meth:`~ArgumentParser.add_argument` is called with
886 ``action='store_const'`` or ``action='append_const'``. These actions add the
887 ``const`` value to one of the attributes of the object returned by :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000888
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300889* When :meth:`~ArgumentParser.add_argument` is called with option strings
890 (like ``-f`` or ``--foo``) and ``nargs='?'``. This creates an optional
Éric Araujod9d7bca2011-08-10 04:19:03 +0200891 argument that can be followed by zero or one command-line arguments.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300892 When parsing the command line, if the option string is encountered with no
Éric Araujofde92422011-08-19 01:30:26 +0200893 command-line argument following it, the value of ``const`` will be assumed instead.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300894 See the nargs_ description for examples.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000895
896The ``const`` keyword argument defaults to ``None``.
897
898
899default
900^^^^^^^
901
902All optional arguments and some positional arguments may be omitted at the
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300903command line. The ``default`` keyword argument of
904:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
Éric Araujofde92422011-08-19 01:30:26 +0200905specifies what value should be used if the command-line argument is not present.
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300906For optional arguments, the ``default`` value is used when the option string
907was not present at the command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000908
909 >>> parser = argparse.ArgumentParser()
910 >>> parser.add_argument('--foo', default=42)
911 >>> parser.parse_args('--foo 2'.split())
912 Namespace(foo='2')
913 >>> parser.parse_args(''.split())
914 Namespace(foo=42)
915
Éric Araujo543edbd2011-08-19 01:45:12 +0200916For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
Éric Araujofde92422011-08-19 01:30:26 +0200917is used when no command-line argument was present::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000918
919 >>> parser = argparse.ArgumentParser()
920 >>> parser.add_argument('foo', nargs='?', default=42)
921 >>> parser.parse_args('a'.split())
922 Namespace(foo='a')
923 >>> parser.parse_args(''.split())
924 Namespace(foo=42)
925
926
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000927Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
928command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000929
930 >>> parser = argparse.ArgumentParser()
931 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
932 >>> parser.parse_args([])
933 Namespace()
934 >>> parser.parse_args(['--foo', '1'])
935 Namespace(foo='1')
936
937
938type
939^^^^
940
Éric Araujod9d7bca2011-08-10 04:19:03 +0200941By default, :class:`ArgumentParser` objects read command-line arguments in as simple
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300942strings. However, quite often the command-line string should instead be
943interpreted as another type, like a :class:`float` or :class:`int`. The
944``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
Éric Araujod9d7bca2011-08-10 04:19:03 +0200945necessary type-checking and type conversions to be performed. Common built-in
Ezio Melotti5569e9b2011-04-22 01:42:10 +0300946types and functions can be used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000947
948 >>> parser = argparse.ArgumentParser()
949 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000950 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000951 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000952 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000953
954To ease the use of various types of files, the argparse module provides the
955factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000956:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000957writable file::
958
959 >>> parser = argparse.ArgumentParser()
960 >>> parser.add_argument('bar', type=argparse.FileType('w'))
961 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000962 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000963
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000964``type=`` can take any callable that takes a single string argument and returns
Éric Araujod9d7bca2011-08-10 04:19:03 +0200965the converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000966
967 >>> def perfect_square(string):
968 ... value = int(string)
969 ... sqrt = math.sqrt(value)
970 ... if sqrt != int(sqrt):
971 ... msg = "%r is not a perfect square" % string
972 ... raise argparse.ArgumentTypeError(msg)
973 ... return value
974 ...
975 >>> parser = argparse.ArgumentParser(prog='PROG')
976 >>> parser.add_argument('foo', type=perfect_square)
977 >>> parser.parse_args('9'.split())
978 Namespace(foo=9)
979 >>> parser.parse_args('7'.split())
980 usage: PROG [-h] foo
981 PROG: error: argument foo: '7' is not a perfect square
982
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000983The choices_ keyword argument may be more convenient for type checkers that
984simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000985
986 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +0000987 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000988 >>> parser.parse_args('7'.split())
989 Namespace(foo=7)
990 >>> parser.parse_args('11'.split())
991 usage: PROG [-h] {5,6,7,8,9}
992 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
993
994See the choices_ section for more details.
995
996
997choices
998^^^^^^^
999
Éric Araujod9d7bca2011-08-10 04:19:03 +02001000Some command-line arguments should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001001These can be handled by passing a container object as the ``choices`` keyword
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001002argument to :meth:`~ArgumentParser.add_argument`. When the command line is
Éric Araujofde92422011-08-19 01:30:26 +02001003parsed, argument values will be checked, and an error message will be displayed if
1004the argument was not one of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001005
1006 >>> parser = argparse.ArgumentParser(prog='PROG')
1007 >>> parser.add_argument('foo', choices='abc')
1008 >>> parser.parse_args('c'.split())
1009 Namespace(foo='c')
1010 >>> parser.parse_args('X'.split())
1011 usage: PROG [-h] {a,b,c}
1012 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
1013
1014Note that inclusion in the ``choices`` container is checked after any type_
1015conversions have been performed, so the type of the objects in the ``choices``
1016container should match the type_ specified::
1017
1018 >>> parser = argparse.ArgumentParser(prog='PROG')
1019 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
1020 >>> parser.parse_args('1j'.split())
1021 Namespace(foo=1j)
1022 >>> parser.parse_args('-- -4'.split())
1023 usage: PROG [-h] {1,1j}
1024 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
1025
1026Any object that supports the ``in`` operator can be passed as the ``choices``
1027value, so :class:`dict` objects, :class:`set` objects, custom containers,
1028etc. are all supported.
1029
1030
1031required
1032^^^^^^^^
1033
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001034In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001035indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001036To make an option *required*, ``True`` can be specified for the ``required=``
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001037keyword argument to :meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001038
1039 >>> parser = argparse.ArgumentParser()
1040 >>> parser.add_argument('--foo', required=True)
1041 >>> parser.parse_args(['--foo', 'BAR'])
1042 Namespace(foo='BAR')
1043 >>> parser.parse_args([])
1044 usage: argparse.py [-h] [--foo FOO]
1045 argparse.py: error: option --foo is required
1046
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001047As the example shows, if an option is marked as ``required``,
1048:meth:`~ArgumentParser.parse_args` will report an error if that option is not
1049present at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001050
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001051.. note::
1052
1053 Required options are generally considered bad form because users expect
1054 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001055
1056
1057help
1058^^^^
1059
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001060The ``help`` value is a string containing a brief description of the argument.
1061When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001062command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001063argument::
1064
1065 >>> parser = argparse.ArgumentParser(prog='frobble')
1066 >>> parser.add_argument('--foo', action='store_true',
1067 ... help='foo the bars before frobbling')
1068 >>> parser.add_argument('bar', nargs='+',
1069 ... help='one of the bars to be frobbled')
1070 >>> parser.parse_args('-h'.split())
1071 usage: frobble [-h] [--foo] bar [bar ...]
1072
1073 positional arguments:
1074 bar one of the bars to be frobbled
1075
1076 optional arguments:
1077 -h, --help show this help message and exit
1078 --foo foo the bars before frobbling
1079
1080The ``help`` strings can include various format specifiers to avoid repetition
1081of things like the program name or the argument default_. The available
1082specifiers include the program name, ``%(prog)s`` and most keyword arguments to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001083:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001084
1085 >>> parser = argparse.ArgumentParser(prog='frobble')
1086 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1087 ... help='the bar to %(prog)s (default: %(default)s)')
1088 >>> parser.print_help()
1089 usage: frobble [-h] [bar]
1090
1091 positional arguments:
1092 bar the bar to frobble (default: 42)
1093
1094 optional arguments:
1095 -h, --help show this help message and exit
1096
Sandro Tosiea320ab2012-01-03 18:37:03 +01001097:mod:`argparse` supports silencing the help entry for certain options, by
1098setting the ``help`` value to ``argparse.SUPPRESS``::
1099
1100 >>> parser = argparse.ArgumentParser(prog='frobble')
1101 >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
1102 >>> parser.print_help()
1103 usage: frobble [-h]
1104
1105 optional arguments:
1106 -h, --help show this help message and exit
1107
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001108
1109metavar
1110^^^^^^^
1111
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001112When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001113to each expected argument. By default, ArgumentParser objects use the dest_
1114value as the "name" of each object. By default, for positional argument
1115actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001116the dest_ value is uppercased. So, a single positional argument with
Eli Benderskya7795db2011-11-11 10:57:01 +02001117``dest='bar'`` will be referred to as ``bar``. A single
Éric Araujofde92422011-08-19 01:30:26 +02001118optional argument ``--foo`` that should be followed by a single command-line argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001119will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001120
1121 >>> parser = argparse.ArgumentParser()
1122 >>> parser.add_argument('--foo')
1123 >>> parser.add_argument('bar')
1124 >>> parser.parse_args('X --foo Y'.split())
1125 Namespace(bar='X', foo='Y')
1126 >>> parser.print_help()
1127 usage: [-h] [--foo FOO] bar
1128
1129 positional arguments:
1130 bar
1131
1132 optional arguments:
1133 -h, --help show this help message and exit
1134 --foo FOO
1135
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001136An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001137
1138 >>> parser = argparse.ArgumentParser()
1139 >>> parser.add_argument('--foo', metavar='YYY')
1140 >>> parser.add_argument('bar', metavar='XXX')
1141 >>> parser.parse_args('X --foo Y'.split())
1142 Namespace(bar='X', foo='Y')
1143 >>> parser.print_help()
1144 usage: [-h] [--foo YYY] XXX
1145
1146 positional arguments:
1147 XXX
1148
1149 optional arguments:
1150 -h, --help show this help message and exit
1151 --foo YYY
1152
1153Note that ``metavar`` only changes the *displayed* name - the name of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001154attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
1155by the dest_ value.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001156
1157Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001158Providing a tuple to ``metavar`` specifies a different display for each of the
1159arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001160
1161 >>> parser = argparse.ArgumentParser(prog='PROG')
1162 >>> parser.add_argument('-x', nargs=2)
1163 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1164 >>> parser.print_help()
1165 usage: PROG [-h] [-x X X] [--foo bar baz]
1166
1167 optional arguments:
1168 -h, --help show this help message and exit
1169 -x X X
1170 --foo bar baz
1171
1172
1173dest
1174^^^^
1175
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001176Most :class:`ArgumentParser` actions add some value as an attribute of the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001177object returned by :meth:`~ArgumentParser.parse_args`. The name of this
1178attribute is determined by the ``dest`` keyword argument of
1179:meth:`~ArgumentParser.add_argument`. For positional argument actions,
1180``dest`` is normally supplied as the first argument to
1181:meth:`~ArgumentParser.add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001182
1183 >>> parser = argparse.ArgumentParser()
1184 >>> parser.add_argument('bar')
1185 >>> parser.parse_args('XXX'.split())
1186 Namespace(bar='XXX')
1187
1188For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001189the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Éric Araujo543edbd2011-08-19 01:45:12 +02001190taking the first long option string and stripping away the initial ``--``
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001191string. If no long option strings were supplied, ``dest`` will be derived from
Éric Araujo543edbd2011-08-19 01:45:12 +02001192the first short option string by stripping the initial ``-`` character. Any
1193internal ``-`` characters will be converted to ``_`` characters to make sure
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001194the string is a valid attribute name. The examples below illustrate this
1195behavior::
1196
1197 >>> parser = argparse.ArgumentParser()
1198 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1199 >>> parser.add_argument('-x', '-y')
1200 >>> parser.parse_args('-f 1 -x 2'.split())
1201 Namespace(foo_bar='1', x='2')
1202 >>> parser.parse_args('--foo 1 -y 2'.split())
1203 Namespace(foo_bar='1', x='2')
1204
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001205``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001206
1207 >>> parser = argparse.ArgumentParser()
1208 >>> parser.add_argument('--foo', dest='bar')
1209 >>> parser.parse_args('--foo XXX'.split())
1210 Namespace(bar='XXX')
1211
1212
1213The parse_args() method
1214-----------------------
1215
Georg Brandle0bf91d2010-10-17 10:34:28 +00001216.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001217
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001218 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001219 namespace. Return the populated namespace.
1220
1221 Previous calls to :meth:`add_argument` determine exactly what objects are
1222 created and how they are assigned. See the documentation for
1223 :meth:`add_argument` for details.
1224
Éric Araujofde92422011-08-19 01:30:26 +02001225 By default, the argument strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001226 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001227
Georg Brandle0bf91d2010-10-17 10:34:28 +00001228
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001229Option value syntax
1230^^^^^^^^^^^^^^^^^^^
1231
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001232The :meth:`~ArgumentParser.parse_args` method supports several ways of
1233specifying the value of an option (if it takes one). In the simplest case, the
1234option and its value are passed as two separate arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001235
1236 >>> parser = argparse.ArgumentParser(prog='PROG')
1237 >>> parser.add_argument('-x')
1238 >>> parser.add_argument('--foo')
1239 >>> parser.parse_args('-x X'.split())
1240 Namespace(foo=None, x='X')
1241 >>> parser.parse_args('--foo FOO'.split())
1242 Namespace(foo='FOO', x=None)
1243
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001244For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001245and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001246separate them::
1247
1248 >>> parser.parse_args('--foo=FOO'.split())
1249 Namespace(foo='FOO', x=None)
1250
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001251For short options (options only one character long), the option and its value
1252can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001253
1254 >>> parser.parse_args('-xX'.split())
1255 Namespace(foo=None, x='X')
1256
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001257Several short options can be joined together, using only a single ``-`` prefix,
1258as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001259
1260 >>> parser = argparse.ArgumentParser(prog='PROG')
1261 >>> parser.add_argument('-x', action='store_true')
1262 >>> parser.add_argument('-y', action='store_true')
1263 >>> parser.add_argument('-z')
1264 >>> parser.parse_args('-xyzZ'.split())
1265 Namespace(x=True, y=True, z='Z')
1266
1267
1268Invalid arguments
1269^^^^^^^^^^^^^^^^^
1270
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001271While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
1272variety of errors, including ambiguous options, invalid types, invalid options,
1273wrong number of positional arguments, etc. When it encounters such an error,
1274it exits and prints the error along with a usage message::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001275
1276 >>> parser = argparse.ArgumentParser(prog='PROG')
1277 >>> parser.add_argument('--foo', type=int)
1278 >>> parser.add_argument('bar', nargs='?')
1279
1280 >>> # invalid type
1281 >>> parser.parse_args(['--foo', 'spam'])
1282 usage: PROG [-h] [--foo FOO] [bar]
1283 PROG: error: argument --foo: invalid int value: 'spam'
1284
1285 >>> # invalid option
1286 >>> parser.parse_args(['--bar'])
1287 usage: PROG [-h] [--foo FOO] [bar]
1288 PROG: error: no such option: --bar
1289
1290 >>> # wrong number of arguments
1291 >>> parser.parse_args(['spam', 'badger'])
1292 usage: PROG [-h] [--foo FOO] [bar]
1293 PROG: error: extra arguments found: badger
1294
1295
Éric Araujo543edbd2011-08-19 01:45:12 +02001296Arguments containing ``-``
1297^^^^^^^^^^^^^^^^^^^^^^^^^^
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001298
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001299The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
1300the user has clearly made a mistake, but some situations are inherently
Éric Araujo543edbd2011-08-19 01:45:12 +02001301ambiguous. For example, the command-line argument ``-1`` could either be an
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001302attempt to specify an option or an attempt to provide a positional argument.
1303The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
Éric Araujo543edbd2011-08-19 01:45:12 +02001304arguments may only begin with ``-`` if they look like negative numbers and
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001305there are no options in the parser that look like negative numbers::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001306
1307 >>> parser = argparse.ArgumentParser(prog='PROG')
1308 >>> parser.add_argument('-x')
1309 >>> parser.add_argument('foo', nargs='?')
1310
1311 >>> # no negative number options, so -1 is a positional argument
1312 >>> parser.parse_args(['-x', '-1'])
1313 Namespace(foo=None, x='-1')
1314
1315 >>> # no negative number options, so -1 and -5 are positional arguments
1316 >>> parser.parse_args(['-x', '-1', '-5'])
1317 Namespace(foo='-5', x='-1')
1318
1319 >>> parser = argparse.ArgumentParser(prog='PROG')
1320 >>> parser.add_argument('-1', dest='one')
1321 >>> parser.add_argument('foo', nargs='?')
1322
1323 >>> # negative number options present, so -1 is an option
1324 >>> parser.parse_args(['-1', 'X'])
1325 Namespace(foo=None, one='X')
1326
1327 >>> # negative number options present, so -2 is an option
1328 >>> parser.parse_args(['-2'])
1329 usage: PROG [-h] [-1 ONE] [foo]
1330 PROG: error: no such option: -2
1331
1332 >>> # negative number options present, so both -1s are options
1333 >>> parser.parse_args(['-1', '-1'])
1334 usage: PROG [-h] [-1 ONE] [foo]
1335 PROG: error: argument -1: expected one argument
1336
Éric Araujo543edbd2011-08-19 01:45:12 +02001337If you have positional arguments that must begin with ``-`` and don't look
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001338like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001339:meth:`~ArgumentParser.parse_args` that everything after that is a positional
1340argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001341
1342 >>> parser.parse_args(['--', '-f'])
1343 Namespace(foo='-f', one=None)
1344
1345
1346Argument abbreviations
1347^^^^^^^^^^^^^^^^^^^^^^
1348
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001349The :meth:`~ArgumentParser.parse_args` method allows long options to be
1350abbreviated if the abbreviation is unambiguous::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001351
1352 >>> parser = argparse.ArgumentParser(prog='PROG')
1353 >>> parser.add_argument('-bacon')
1354 >>> parser.add_argument('-badger')
1355 >>> parser.parse_args('-bac MMM'.split())
1356 Namespace(bacon='MMM', badger=None)
1357 >>> parser.parse_args('-bad WOOD'.split())
1358 Namespace(bacon=None, badger='WOOD')
1359 >>> parser.parse_args('-ba BA'.split())
1360 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1361 PROG: error: ambiguous option: -ba could match -badger, -bacon
1362
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001363An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001364
1365
1366Beyond ``sys.argv``
1367^^^^^^^^^^^^^^^^^^^
1368
Éric Araujod9d7bca2011-08-10 04:19:03 +02001369Sometimes it may be useful to have an ArgumentParser parse arguments other than those
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001370of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001371:meth:`~ArgumentParser.parse_args`. This is useful for testing at the
1372interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001373
1374 >>> parser = argparse.ArgumentParser()
1375 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001376 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001377 ... nargs='+', help='an integer in the range 0..9')
1378 >>> parser.add_argument(
1379 ... '--sum', dest='accumulate', action='store_const', const=sum,
1380 ... default=max, help='sum the integers (default: find the max)')
1381 >>> parser.parse_args(['1', '2', '3', '4'])
1382 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1383 >>> parser.parse_args('1 2 3 4 --sum'.split())
1384 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1385
1386
Steven Bethardd8f2d502011-03-26 19:50:06 +01001387The Namespace object
1388^^^^^^^^^^^^^^^^^^^^
1389
Éric Araujo63b18a42011-07-29 17:59:17 +02001390.. class:: Namespace
1391
1392 Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
1393 an object holding attributes and return it.
1394
1395This class is deliberately simple, just an :class:`object` subclass with a
1396readable string representation. If you prefer to have dict-like view of the
1397attributes, you can use the standard Python idiom, :func:`vars`::
Steven Bethardd8f2d502011-03-26 19:50:06 +01001398
1399 >>> parser = argparse.ArgumentParser()
1400 >>> parser.add_argument('--foo')
1401 >>> args = parser.parse_args(['--foo', 'BAR'])
1402 >>> vars(args)
1403 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001404
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001405It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001406already existing object, rather than a new :class:`Namespace` object. This can
1407be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001408
Éric Araujo28053fb2010-11-22 03:09:19 +00001409 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001410 ... pass
1411 ...
1412 >>> c = C()
1413 >>> parser = argparse.ArgumentParser()
1414 >>> parser.add_argument('--foo')
1415 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1416 >>> c.foo
1417 'BAR'
1418
1419
1420Other utilities
1421---------------
1422
1423Sub-commands
1424^^^^^^^^^^^^
1425
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001426.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001427
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001428 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001429 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001430 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001431 this way can be a particularly good idea when a program performs several
1432 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001433 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001434 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1435 called with no arguments and returns an special action object. This object
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001436 has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
1437 command name and any :class:`ArgumentParser` constructor arguments, and
1438 returns an :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001439
1440 Some example usage::
1441
1442 >>> # create the top-level parser
1443 >>> parser = argparse.ArgumentParser(prog='PROG')
1444 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1445 >>> subparsers = parser.add_subparsers(help='sub-command help')
1446 >>>
1447 >>> # create the parser for the "a" command
1448 >>> parser_a = subparsers.add_parser('a', help='a help')
1449 >>> parser_a.add_argument('bar', type=int, help='bar help')
1450 >>>
1451 >>> # create the parser for the "b" command
1452 >>> parser_b = subparsers.add_parser('b', help='b help')
1453 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1454 >>>
Éric Araujofde92422011-08-19 01:30:26 +02001455 >>> # parse some argument lists
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001456 >>> parser.parse_args(['a', '12'])
1457 Namespace(bar=12, foo=False)
1458 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1459 Namespace(baz='Z', foo=True)
1460
1461 Note that the object returned by :meth:`parse_args` will only contain
1462 attributes for the main parser and the subparser that was selected by the
1463 command line (and not any other subparsers). So in the example above, when
Éric Araujo543edbd2011-08-19 01:45:12 +02001464 the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
1465 present, and when the ``b`` command is specified, only the ``foo`` and
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001466 ``baz`` attributes are present.
1467
1468 Similarly, when a help message is requested from a subparser, only the help
1469 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001470 include parent parser or sibling parser messages. (A help message for each
1471 subparser command, however, can be given by supplying the ``help=`` argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001472 to :meth:`add_parser` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001473
1474 ::
1475
1476 >>> parser.parse_args(['--help'])
1477 usage: PROG [-h] [--foo] {a,b} ...
1478
1479 positional arguments:
1480 {a,b} sub-command help
1481 a a help
1482 b b help
1483
1484 optional arguments:
1485 -h, --help show this help message and exit
1486 --foo foo help
1487
1488 >>> parser.parse_args(['a', '--help'])
1489 usage: PROG a [-h] bar
1490
1491 positional arguments:
1492 bar bar help
1493
1494 optional arguments:
1495 -h, --help show this help message and exit
1496
1497 >>> parser.parse_args(['b', '--help'])
1498 usage: PROG b [-h] [--baz {X,Y,Z}]
1499
1500 optional arguments:
1501 -h, --help show this help message and exit
1502 --baz {X,Y,Z} baz help
1503
1504 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1505 keyword arguments. When either is present, the subparser's commands will
1506 appear in their own group in the help output. For example::
1507
1508 >>> parser = argparse.ArgumentParser()
1509 >>> subparsers = parser.add_subparsers(title='subcommands',
1510 ... description='valid subcommands',
1511 ... help='additional help')
1512 >>> subparsers.add_parser('foo')
1513 >>> subparsers.add_parser('bar')
1514 >>> parser.parse_args(['-h'])
1515 usage: [-h] {foo,bar} ...
1516
1517 optional arguments:
1518 -h, --help show this help message and exit
1519
1520 subcommands:
1521 valid subcommands
1522
1523 {foo,bar} additional help
1524
Steven Bethardfd311a72010-12-18 11:19:23 +00001525 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1526 which allows multiple strings to refer to the same subparser. This example,
1527 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1528
1529 >>> parser = argparse.ArgumentParser()
1530 >>> subparsers = parser.add_subparsers()
1531 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1532 >>> checkout.add_argument('foo')
1533 >>> parser.parse_args(['co', 'bar'])
1534 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001535
1536 One particularly effective way of handling sub-commands is to combine the use
1537 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1538 that each subparser knows which Python function it should execute. For
1539 example::
1540
1541 >>> # sub-command functions
1542 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001543 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001544 ...
1545 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001546 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001547 ...
1548 >>> # create the top-level parser
1549 >>> parser = argparse.ArgumentParser()
1550 >>> subparsers = parser.add_subparsers()
1551 >>>
1552 >>> # create the parser for the "foo" command
1553 >>> parser_foo = subparsers.add_parser('foo')
1554 >>> parser_foo.add_argument('-x', type=int, default=1)
1555 >>> parser_foo.add_argument('y', type=float)
1556 >>> parser_foo.set_defaults(func=foo)
1557 >>>
1558 >>> # create the parser for the "bar" command
1559 >>> parser_bar = subparsers.add_parser('bar')
1560 >>> parser_bar.add_argument('z')
1561 >>> parser_bar.set_defaults(func=bar)
1562 >>>
1563 >>> # parse the args and call whatever function was selected
1564 >>> args = parser.parse_args('foo 1 -x 2'.split())
1565 >>> args.func(args)
1566 2.0
1567 >>>
1568 >>> # parse the args and call whatever function was selected
1569 >>> args = parser.parse_args('bar XYZYX'.split())
1570 >>> args.func(args)
1571 ((XYZYX))
1572
Steven Bethardfd311a72010-12-18 11:19:23 +00001573 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001574 appropriate function after argument parsing is complete. Associating
1575 functions with actions like this is typically the easiest way to handle the
1576 different actions for each of your subparsers. However, if it is necessary
1577 to check the name of the subparser that was invoked, the ``dest`` keyword
1578 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001579
1580 >>> parser = argparse.ArgumentParser()
1581 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1582 >>> subparser1 = subparsers.add_parser('1')
1583 >>> subparser1.add_argument('-x')
1584 >>> subparser2 = subparsers.add_parser('2')
1585 >>> subparser2.add_argument('y')
1586 >>> parser.parse_args(['2', 'frobble'])
1587 Namespace(subparser_name='2', y='frobble')
1588
1589
1590FileType objects
1591^^^^^^^^^^^^^^^^
1592
1593.. class:: FileType(mode='r', bufsize=None)
1594
1595 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001596 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
Éric Araujod9d7bca2011-08-10 04:19:03 +02001597 :class:`FileType` objects as their type will open command-line arguments as files
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001598 with the requested modes and buffer sizes:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001599
1600 >>> parser = argparse.ArgumentParser()
1601 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1602 >>> parser.parse_args(['--output', 'out'])
Georg Brandl04536b02011-01-09 09:31:01 +00001603 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001604
1605 FileType objects understand the pseudo-argument ``'-'`` and automatically
1606 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1607 ``sys.stdout`` for writable :class:`FileType` objects:
1608
1609 >>> parser = argparse.ArgumentParser()
1610 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1611 >>> parser.parse_args(['-'])
Georg Brandl04536b02011-01-09 09:31:01 +00001612 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001613
1614
1615Argument groups
1616^^^^^^^^^^^^^^^
1617
Georg Brandle0bf91d2010-10-17 10:34:28 +00001618.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001619
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001620 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001621 "positional arguments" and "optional arguments" when displaying help
1622 messages. When there is a better conceptual grouping of arguments than this
1623 default one, appropriate groups can be created using the
1624 :meth:`add_argument_group` method::
1625
1626 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1627 >>> group = parser.add_argument_group('group')
1628 >>> group.add_argument('--foo', help='foo help')
1629 >>> group.add_argument('bar', help='bar help')
1630 >>> parser.print_help()
1631 usage: PROG [--foo FOO] bar
1632
1633 group:
1634 bar bar help
1635 --foo FOO foo help
1636
1637 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001638 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1639 :class:`ArgumentParser`. When an argument is added to the group, the parser
1640 treats it just like a normal argument, but displays the argument in a
1641 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001642 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001643 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001644
1645 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1646 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1647 >>> group1.add_argument('foo', help='foo help')
1648 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1649 >>> group2.add_argument('--bar', help='bar help')
1650 >>> parser.print_help()
1651 usage: PROG [--bar BAR] foo
1652
1653 group1:
1654 group1 description
1655
1656 foo foo help
1657
1658 group2:
1659 group2 description
1660
1661 --bar BAR bar help
1662
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001663 Note that any arguments not your user defined groups will end up back in the
1664 usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001665
1666
1667Mutual exclusion
1668^^^^^^^^^^^^^^^^
1669
Georg Brandle0bf91d2010-10-17 10:34:28 +00001670.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001671
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001672 Create a mutually exclusive group. :mod:`argparse` will make sure that only
1673 one of the arguments in the mutually exclusive group was present on the
1674 command line::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001675
1676 >>> parser = argparse.ArgumentParser(prog='PROG')
1677 >>> group = parser.add_mutually_exclusive_group()
1678 >>> group.add_argument('--foo', action='store_true')
1679 >>> group.add_argument('--bar', action='store_false')
1680 >>> parser.parse_args(['--foo'])
1681 Namespace(bar=True, foo=True)
1682 >>> parser.parse_args(['--bar'])
1683 Namespace(bar=False, foo=False)
1684 >>> parser.parse_args(['--foo', '--bar'])
1685 usage: PROG [-h] [--foo | --bar]
1686 PROG: error: argument --bar: not allowed with argument --foo
1687
Georg Brandle0bf91d2010-10-17 10:34:28 +00001688 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001689 argument, to indicate that at least one of the mutually exclusive arguments
1690 is required::
1691
1692 >>> parser = argparse.ArgumentParser(prog='PROG')
1693 >>> group = parser.add_mutually_exclusive_group(required=True)
1694 >>> group.add_argument('--foo', action='store_true')
1695 >>> group.add_argument('--bar', action='store_false')
1696 >>> parser.parse_args([])
1697 usage: PROG [-h] (--foo | --bar)
1698 PROG: error: one of the arguments --foo --bar is required
1699
1700 Note that currently mutually exclusive argument groups do not support the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001701 *title* and *description* arguments of
1702 :meth:`~ArgumentParser.add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001703
1704
1705Parser defaults
1706^^^^^^^^^^^^^^^
1707
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001708.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001709
1710 Most of the time, the attributes of the object returned by :meth:`parse_args`
Éric Araujod9d7bca2011-08-10 04:19:03 +02001711 will be fully determined by inspecting the command-line arguments and the argument
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001712 actions. :meth:`set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001713 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001714 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001715
1716 >>> parser = argparse.ArgumentParser()
1717 >>> parser.add_argument('foo', type=int)
1718 >>> parser.set_defaults(bar=42, baz='badger')
1719 >>> parser.parse_args(['736'])
1720 Namespace(bar=42, baz='badger', foo=736)
1721
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001722 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001723
1724 >>> parser = argparse.ArgumentParser()
1725 >>> parser.add_argument('--foo', default='bar')
1726 >>> parser.set_defaults(foo='spam')
1727 >>> parser.parse_args([])
1728 Namespace(foo='spam')
1729
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001730 Parser-level defaults can be particularly useful when working with multiple
1731 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1732 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001733
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001734.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001735
1736 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001737 :meth:`~ArgumentParser.add_argument` or by
1738 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001739
1740 >>> parser = argparse.ArgumentParser()
1741 >>> parser.add_argument('--foo', default='badger')
1742 >>> parser.get_default('foo')
1743 'badger'
1744
1745
1746Printing help
1747^^^^^^^^^^^^^
1748
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001749In most typical applications, :meth:`~ArgumentParser.parse_args` will take
1750care of formatting and printing any usage or error messages. However, several
1751formatting methods are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001752
Georg Brandle0bf91d2010-10-17 10:34:28 +00001753.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001754
1755 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001756 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001757 assumed.
1758
Georg Brandle0bf91d2010-10-17 10:34:28 +00001759.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001760
1761 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001762 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001763 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001764
1765There are also variants of these methods that simply return a string instead of
1766printing it:
1767
Georg Brandle0bf91d2010-10-17 10:34:28 +00001768.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001769
1770 Return a string containing a brief description of how the
1771 :class:`ArgumentParser` should be invoked on the command line.
1772
Georg Brandle0bf91d2010-10-17 10:34:28 +00001773.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001774
1775 Return a string containing a help message, including the program usage and
1776 information about the arguments registered with the :class:`ArgumentParser`.
1777
1778
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001779Partial parsing
1780^^^^^^^^^^^^^^^
1781
Georg Brandle0bf91d2010-10-17 10:34:28 +00001782.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001783
Georg Brandl69518bc2011-04-16 16:44:54 +02001784Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001785the remaining arguments on to another script or program. In these cases, the
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001786:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001787:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1788extra arguments are present. Instead, it returns a two item tuple containing
1789the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001790
1791::
1792
1793 >>> parser = argparse.ArgumentParser()
1794 >>> parser.add_argument('--foo', action='store_true')
1795 >>> parser.add_argument('bar')
1796 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1797 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1798
1799
1800Customizing file parsing
1801^^^^^^^^^^^^^^^^^^^^^^^^
1802
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001803.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001804
Georg Brandle0bf91d2010-10-17 10:34:28 +00001805 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001806 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001807 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1808 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001809
Georg Brandle0bf91d2010-10-17 10:34:28 +00001810 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001811 the argument file. It returns a list of arguments parsed from this string.
1812 The method is called once per line read from the argument file, in order.
1813
1814 A useful override of this method is one that treats each space-separated word
1815 as an argument::
1816
1817 def convert_arg_line_to_args(self, arg_line):
1818 for arg in arg_line.split():
1819 if not arg.strip():
1820 continue
1821 yield arg
1822
1823
Georg Brandl93754922010-10-17 10:28:04 +00001824Exiting methods
1825^^^^^^^^^^^^^^^
1826
1827.. method:: ArgumentParser.exit(status=0, message=None)
1828
1829 This method terminates the program, exiting with the specified *status*
1830 and, if given, it prints a *message* before that.
1831
1832.. method:: ArgumentParser.error(message)
1833
1834 This method prints a usage message including the *message* to the
Senthil Kumaran86a1a892011-08-03 07:42:18 +08001835 standard error and terminates the program with a status code of 2.
Georg Brandl93754922010-10-17 10:28:04 +00001836
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001837.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001838
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001839Upgrading optparse code
1840-----------------------
1841
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001842Originally, the :mod:`argparse` module had attempted to maintain compatibility
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001843with :mod:`optparse`. However, :mod:`optparse` was difficult to extend
1844transparently, particularly with the changes required to support the new
1845``nargs=`` specifiers and better usage messages. When most everything in
1846:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
1847longer seemed practical to try to maintain the backwards compatibility.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001848
Ezio Melotti0ee9c1b2011-04-21 16:12:17 +03001849A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001850
Ezio Melotti5569e9b2011-04-22 01:42:10 +03001851* Replace all :meth:`optparse.OptionParser.add_option` calls with
1852 :meth:`ArgumentParser.add_argument` calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001853
1854* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001855 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1856 calls for the positional arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001857
1858* Replace callback actions and the ``callback_*`` keyword arguments with
1859 ``type`` or ``action`` arguments.
1860
1861* Replace string names for ``type`` keyword arguments with the corresponding
1862 type objects (e.g. int, float, complex, etc).
1863
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001864* Replace :class:`optparse.Values` with :class:`Namespace` and
1865 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1866 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001867
1868* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
Ezio Melotticca4ef82011-04-21 15:26:46 +03001869 the standard Python syntax to use dictionaries to format strings, that is,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001870 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001871
1872* Replace the OptionParser constructor ``version`` argument with a call to
1873 ``parser.add_argument('--version', action='version', version='<the version>')``