blob: c8b0a613abc64360e126cb1574fcc2984645b62c [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
Ezio Melotti2409d772011-04-16 23:13:50 +03005 :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**Source code:** :source:`Lib/argparse.py`
10
11.. versionadded:: 3.2
12
13--------------
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
Benjamin Peterson98047eb2010-03-03 02:07:08 +000082parse 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
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000100Later, calling :meth:`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
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000110:class:`ArgumentParser` parses args through the
Georg Brandl69518bc2011-04-16 16:44:54 +0200111:meth:`~ArgumentParser.parse_args` method. This will inspect the command line,
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000112convert each arg to the appropriate type and then invoke the appropriate action.
113In most cases, this means a simple 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
121command-line args 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:
158 :data:`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
247if the ``prefix_chars=`` is specified and does not include ``'-'``, in
248which 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
263Most 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
276characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
277disallowed.
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
298:meth:`convert_arg_line_to_args`) and are treated as if they were in the same
299place as the original file referencing argument on the command line. So in the
300example above, the expression ``['-f', 'foo', '@args.txt']`` is considered
301equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
302
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
311:meth:`add_argument` or by calling the :meth:`set_defaults` methods with a
312specific set of name-value pairs. Sometimes however, it may be useful to
313specify a single parser-wide default for arguments. This can be accomplished by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000314passing the ``argument_default=`` keyword argument to :class:`ArgumentParser`.
315For example, to globally suppress attribute creation on :meth:`parse_args`
316calls, we supply ``argument_default=SUPPRESS``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000317
318 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
319 >>> parser.add_argument('--foo')
320 >>> parser.add_argument('bar', nargs='?')
321 >>> parser.parse_args(['--foo', '1', 'BAR'])
322 Namespace(bar='BAR', foo='1')
323 >>> parser.parse_args([])
324 Namespace()
325
326
327parents
328^^^^^^^
329
330Sometimes, several parsers share a common set of arguments. Rather than
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000331repeating the definitions of these arguments, a single parser with all the
332shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
333can be used. The ``parents=`` argument takes a list of :class:`ArgumentParser`
334objects, collects all the positional and optional actions from them, and adds
335these actions to the :class:`ArgumentParser` object being constructed::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000336
337 >>> parent_parser = argparse.ArgumentParser(add_help=False)
338 >>> parent_parser.add_argument('--parent', type=int)
339
340 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
341 >>> foo_parser.add_argument('foo')
342 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
343 Namespace(foo='XXX', parent=2)
344
345 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
346 >>> bar_parser.add_argument('--bar')
347 >>> bar_parser.parse_args(['--bar', 'YYY'])
348 Namespace(bar='YYY', parent=None)
349
350Note that most parent parsers will specify ``add_help=False``. Otherwise, the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000351:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
352and one in the child) and raise an error.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000353
Steven Bethardd186f992011-03-26 21:49:00 +0100354.. note::
355 You must fully initialize the parsers before passing them via ``parents=``.
356 If you change the parent parsers after the child parser, those changes will
357 not be reflected in the child.
358
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000359
360formatter_class
361^^^^^^^^^^^^^^^
362
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000363:class:`ArgumentParser` objects allow the help formatting to be customized by
Steven Bethard0331e902011-03-26 14:48:04 +0100364specifying an alternate formatting class.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000365
Steven Bethard0331e902011-03-26 14:48:04 +0100366:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
367more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000368By default, :class:`ArgumentParser` objects line-wrap the description_ and
369epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000370
371 >>> parser = argparse.ArgumentParser(
372 ... prog='PROG',
373 ... description='''this description
374 ... was indented weird
375 ... but that is okay''',
376 ... epilog='''
377 ... likewise for this epilog whose whitespace will
378 ... be cleaned up and whose words will be wrapped
379 ... across a couple lines''')
380 >>> parser.print_help()
381 usage: PROG [-h]
382
383 this description was indented weird but that is okay
384
385 optional arguments:
386 -h, --help show this help message and exit
387
388 likewise for this epilog whose whitespace will be cleaned up and whose words
389 will be wrapped across a couple lines
390
Steven Bethard0331e902011-03-26 14:48:04 +0100391Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000392indicates that description_ and epilog_ are already correctly formatted and
393should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000394
395 >>> parser = argparse.ArgumentParser(
396 ... prog='PROG',
397 ... formatter_class=argparse.RawDescriptionHelpFormatter,
398 ... description=textwrap.dedent('''\
399 ... Please do not mess up this text!
400 ... --------------------------------
401 ... I have indented it
402 ... exactly the way
403 ... I want it
404 ... '''))
405 >>> parser.print_help()
406 usage: PROG [-h]
407
408 Please do not mess up this text!
409 --------------------------------
410 I have indented it
411 exactly the way
412 I want it
413
414 optional arguments:
415 -h, --help show this help message and exit
416
Steven Bethard0331e902011-03-26 14:48:04 +0100417:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000418including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000419
Steven Bethard0331e902011-03-26 14:48:04 +0100420:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
421default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000422
423 >>> parser = argparse.ArgumentParser(
424 ... prog='PROG',
425 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
426 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
427 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
428 >>> parser.print_help()
429 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
430
431 positional arguments:
432 bar BAR! (default: [1, 2, 3])
433
434 optional arguments:
435 -h, --help show this help message and exit
436 --foo FOO FOO! (default: 42)
437
Steven Bethard0331e902011-03-26 14:48:04 +0100438:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
439argument as as the display name for its values (rather than using the dest_
440as the regular formatter does)::
441
442 >>> parser = argparse.ArgumentParser(
443 ... prog='PROG',
444 ... formatter_class=argparse.MetavarTypeHelpFormatter)
445 >>> parser.add_argument('--foo', type=int)
446 >>> parser.add_argument('bar', type=float)
447 >>> parser.print_help()
448 usage: PROG [-h] [--foo int] float
449
450 positional arguments:
451 float
452
453 optional arguments:
454 -h, --help show this help message and exit
455 --foo int
456
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000457
458conflict_handler
459^^^^^^^^^^^^^^^^
460
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000461:class:`ArgumentParser` objects do not allow two actions with the same option
462string. By default, :class:`ArgumentParser` objects raises an exception if an
463attempt is made to create an argument with an option string that is already in
464use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000465
466 >>> parser = argparse.ArgumentParser(prog='PROG')
467 >>> parser.add_argument('-f', '--foo', help='old foo help')
468 >>> parser.add_argument('--foo', help='new foo help')
469 Traceback (most recent call last):
470 ..
471 ArgumentError: argument --foo: conflicting option string(s): --foo
472
473Sometimes (e.g. when using parents_) it may be useful to simply override any
474older arguments with the same option string. To get this behavior, the value
475``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000476:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000477
478 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
479 >>> parser.add_argument('-f', '--foo', help='old foo help')
480 >>> parser.add_argument('--foo', help='new foo help')
481 >>> parser.print_help()
482 usage: PROG [-h] [-f FOO] [--foo FOO]
483
484 optional arguments:
485 -h, --help show this help message and exit
486 -f FOO old foo help
487 --foo FOO new foo help
488
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000489Note that :class:`ArgumentParser` objects only remove an action if all of its
490option strings are overridden. So, in the example above, the old ``-f/--foo``
491action is retained as the ``-f`` action, because only the ``--foo`` option
492string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000493
494
495prog
496^^^^
497
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000498By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
499how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000500always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000501invoked on the command line. For example, consider a file named
502``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000503
504 import argparse
505 parser = argparse.ArgumentParser()
506 parser.add_argument('--foo', help='foo help')
507 args = parser.parse_args()
508
509The help for this program will display ``myprogram.py`` as the program name
510(regardless of where the program was invoked from)::
511
512 $ python myprogram.py --help
513 usage: myprogram.py [-h] [--foo FOO]
514
515 optional arguments:
516 -h, --help show this help message and exit
517 --foo FOO foo help
518 $ cd ..
519 $ python subdir\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
526To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000527``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000528
529 >>> parser = argparse.ArgumentParser(prog='myprogram')
530 >>> parser.print_help()
531 usage: myprogram [-h]
532
533 optional arguments:
534 -h, --help show this help message and exit
535
536Note that the program name, whether determined from ``sys.argv[0]`` or from the
537``prog=`` argument, is available to help messages using the ``%(prog)s`` format
538specifier.
539
540::
541
542 >>> parser = argparse.ArgumentParser(prog='myprogram')
543 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
544 >>> parser.print_help()
545 usage: myprogram [-h] [--foo FOO]
546
547 optional arguments:
548 -h, --help show this help message and exit
549 --foo FOO foo of the myprogram program
550
551
552usage
553^^^^^
554
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000555By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000556arguments it contains::
557
558 >>> parser = argparse.ArgumentParser(prog='PROG')
559 >>> parser.add_argument('--foo', nargs='?', help='foo help')
560 >>> parser.add_argument('bar', nargs='+', help='bar help')
561 >>> parser.print_help()
562 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
563
564 positional arguments:
565 bar bar help
566
567 optional arguments:
568 -h, --help show this help message and exit
569 --foo [FOO] foo help
570
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000571The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000572
573 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
574 >>> parser.add_argument('--foo', nargs='?', help='foo help')
575 >>> parser.add_argument('bar', nargs='+', help='bar help')
576 >>> parser.print_help()
577 usage: PROG [options]
578
579 positional arguments:
580 bar bar help
581
582 optional arguments:
583 -h, --help show this help message and exit
584 --foo [FOO] foo help
585
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000586The ``%(prog)s`` format specifier is available to fill in the program name in
587your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000588
589
590The add_argument() method
591-------------------------
592
Georg Brandlc9007082011-01-09 09:04:08 +0000593.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
594 [const], [default], [type], [choices], [required], \
595 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000596
Georg Brandl69518bc2011-04-16 16:44:54 +0200597 Define how a single command-line argument should be parsed. Each parameter
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000598 has its own more detailed description below, but in short they are:
599
600 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
601 or ``-f, --foo``
602
603 * action_ - The basic type of action to be taken when this argument is
Georg Brandl69518bc2011-04-16 16:44:54 +0200604 encountered at the command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000605
606 * nargs_ - The number of command-line arguments that should be consumed.
607
608 * const_ - A constant value required by some action_ and nargs_ selections.
609
610 * default_ - The value produced if the argument is absent from the
Georg Brandl69518bc2011-04-16 16:44:54 +0200611 command line.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000612
Ezio Melotti2409d772011-04-16 23:13:50 +0300613 * type_ - The type to which the command-line argument should be converted.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000614
615 * choices_ - A container of the allowable values for the argument.
616
617 * required_ - Whether or not the command-line option may be omitted
618 (optionals only).
619
620 * help_ - A brief description of what the argument does.
621
622 * metavar_ - A name for the argument in usage messages.
623
624 * dest_ - The name of the attribute to be added to the object returned by
625 :meth:`parse_args`.
626
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000627The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000628
Georg Brandle0bf91d2010-10-17 10:34:28 +0000629
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000630name or flags
631^^^^^^^^^^^^^
632
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000633The :meth:`add_argument` method must know whether an optional argument, like
634``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
635expected. The first arguments passed to :meth:`add_argument` must therefore be
636either a series of flags, or a simple argument name. For example, an optional
637argument could be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000638
639 >>> parser.add_argument('-f', '--foo')
640
641while a positional argument could be created like::
642
643 >>> parser.add_argument('bar')
644
645When :meth:`parse_args` is called, optional arguments will be identified by the
646``-`` prefix, and the remaining arguments will be assumed to be positional::
647
648 >>> parser = argparse.ArgumentParser(prog='PROG')
649 >>> parser.add_argument('-f', '--foo')
650 >>> parser.add_argument('bar')
651 >>> parser.parse_args(['BAR'])
652 Namespace(bar='BAR', foo=None)
653 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
654 Namespace(bar='BAR', foo='FOO')
655 >>> parser.parse_args(['--foo', 'FOO'])
656 usage: PROG [-h] [-f FOO] bar
657 PROG: error: too few arguments
658
Georg Brandle0bf91d2010-10-17 10:34:28 +0000659
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000660action
661^^^^^^
662
663:class:`ArgumentParser` objects associate command-line args with actions. These
664actions can do just about anything with the command-line args associated with
665them, though most actions simply add an attribute to the object returned by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000666:meth:`parse_args`. The ``action`` keyword argument specifies how the
667command-line args should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000668
669* ``'store'`` - This just stores the argument's value. This is the default
670 action. For example::
671
672 >>> parser = argparse.ArgumentParser()
673 >>> parser.add_argument('--foo')
674 >>> parser.parse_args('--foo 1'.split())
675 Namespace(foo='1')
676
677* ``'store_const'`` - This stores the value specified by the const_ keyword
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000678 argument. (Note that the const_ keyword argument defaults to the rather
679 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
680 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000681
682 >>> parser = argparse.ArgumentParser()
683 >>> parser.add_argument('--foo', action='store_const', const=42)
684 >>> parser.parse_args('--foo'.split())
685 Namespace(foo=42)
686
687* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000688 ``False`` respectively. These are special cases of ``'store_const'``. For
689 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000690
691 >>> parser = argparse.ArgumentParser()
692 >>> parser.add_argument('--foo', action='store_true')
693 >>> parser.add_argument('--bar', action='store_false')
694 >>> parser.parse_args('--foo --bar'.split())
695 Namespace(bar=False, foo=True)
696
697* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000698 list. This is useful to allow an option to be specified multiple times.
699 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000700
701 >>> parser = argparse.ArgumentParser()
702 >>> parser.add_argument('--foo', action='append')
703 >>> parser.parse_args('--foo 1 --foo 2'.split())
704 Namespace(foo=['1', '2'])
705
706* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000707 the const_ keyword argument to the list. (Note that the const_ keyword
708 argument defaults to ``None``.) The ``'append_const'`` action is typically
709 useful when multiple arguments need to store constants to the same list. For
710 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000711
712 >>> parser = argparse.ArgumentParser()
713 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
714 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
715 >>> parser.parse_args('--str --int'.split())
716 Namespace(types=[<type 'str'>, <type 'int'>])
717
718* ``'version'`` - This expects a ``version=`` keyword argument in the
719 :meth:`add_argument` call, and prints version information and exits when
720 invoked.
721
722 >>> import argparse
723 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000724 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
725 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000726 PROG 2.0
727
728You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000729the Action API. The easiest way to do this is to extend
730:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
731``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000732
733* ``parser`` - The ArgumentParser object which contains this action.
734
735* ``namespace`` - The namespace object that will be returned by
736 :meth:`parse_args`. Most actions add an attribute to this object.
737
738* ``values`` - The associated command-line args, with any type-conversions
739 applied. (Type-conversions are specified with the type_ keyword argument to
740 :meth:`add_argument`.
741
742* ``option_string`` - The option string that was used to invoke this action.
743 The ``option_string`` argument is optional, and will be absent if the action
744 is associated with a positional argument.
745
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000746An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000747
748 >>> class FooAction(argparse.Action):
749 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000750 ... print('%r %r %r' % (namespace, values, option_string))
751 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000752 ...
753 >>> parser = argparse.ArgumentParser()
754 >>> parser.add_argument('--foo', action=FooAction)
755 >>> parser.add_argument('bar', action=FooAction)
756 >>> args = parser.parse_args('1 --foo 2'.split())
757 Namespace(bar=None, foo=None) '1' None
758 Namespace(bar='1', foo=None) '2' '--foo'
759 >>> args
760 Namespace(bar='1', foo='2')
761
762
763nargs
764^^^^^
765
766ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000767single action to be taken. The ``nargs`` keyword argument associates a
768different number of command-line arguments with a single action.. The supported
769values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000770
Georg Brandl69518bc2011-04-16 16:44:54 +0200771* N (an integer). N args from the command line will be gathered together into a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000772 list. For example::
773
Georg Brandl682d7e02010-10-06 10:26:05 +0000774 >>> parser = argparse.ArgumentParser()
775 >>> parser.add_argument('--foo', nargs=2)
776 >>> parser.add_argument('bar', nargs=1)
777 >>> parser.parse_args('c --foo a b'.split())
778 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000779
Georg Brandl682d7e02010-10-06 10:26:05 +0000780 Note that ``nargs=1`` produces a list of one item. This is different from
781 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000782
Georg Brandl69518bc2011-04-16 16:44:54 +0200783* ``'?'``. One arg will be consumed from the command line if possible, and
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000784 produced as a single item. If no command-line arg is present, the value from
785 default_ will be produced. Note that for optional arguments, there is an
786 additional case - the option string is present but not followed by a
787 command-line arg. In this case the value from const_ will be produced. Some
788 examples to illustrate this::
789
790 >>> parser = argparse.ArgumentParser()
791 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
792 >>> parser.add_argument('bar', nargs='?', default='d')
793 >>> parser.parse_args('XX --foo YY'.split())
794 Namespace(bar='XX', foo='YY')
795 >>> parser.parse_args('XX --foo'.split())
796 Namespace(bar='XX', foo='c')
797 >>> parser.parse_args(''.split())
798 Namespace(bar='d', foo='d')
799
800 One of the more common uses of ``nargs='?'`` is to allow optional input and
801 output files::
802
803 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000804 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
805 ... default=sys.stdin)
806 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
807 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000808 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000809 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
810 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000811 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000812 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
813 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000814
815* ``'*'``. All command-line args present are gathered into a list. Note that
816 it generally doesn't make much sense to have more than one positional argument
817 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
818 possible. For example::
819
820 >>> parser = argparse.ArgumentParser()
821 >>> parser.add_argument('--foo', nargs='*')
822 >>> parser.add_argument('--bar', nargs='*')
823 >>> parser.add_argument('baz', nargs='*')
824 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
825 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
826
827* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
828 list. Additionally, an error message will be generated if there wasn't at
829 least one command-line arg present. For example::
830
831 >>> parser = argparse.ArgumentParser(prog='PROG')
832 >>> parser.add_argument('foo', nargs='+')
833 >>> parser.parse_args('a b'.split())
834 Namespace(foo=['a', 'b'])
835 >>> parser.parse_args(''.split())
836 usage: PROG [-h] foo [foo ...]
837 PROG: error: too few arguments
838
839If the ``nargs`` keyword argument is not provided, the number of args consumed
840is determined by the action_. Generally this means a single command-line arg
841will be consumed and a single item (not a list) will be produced.
842
843
844const
845^^^^^
846
847The ``const`` argument of :meth:`add_argument` is used to hold constant values
848that are not read from the command line but are required for the various
849ArgumentParser actions. The two most common uses of it are:
850
851* When :meth:`add_argument` is called with ``action='store_const'`` or
852 ``action='append_const'``. These actions add the ``const`` value to one of
853 the attributes of the object returned by :meth:`parse_args`. See the action_
854 description for examples.
855
856* When :meth:`add_argument` is called with option strings (like ``-f`` or
857 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
Georg Brandl69518bc2011-04-16 16:44:54 +0200858 followed by zero or one command-line args. When parsing the command line, if
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000859 the option string is encountered with no command-line arg following it, the
860 value of ``const`` will be assumed instead. See the nargs_ description for
861 examples.
862
863The ``const`` keyword argument defaults to ``None``.
864
865
866default
867^^^^^^^
868
869All optional arguments and some positional arguments may be omitted at the
Georg Brandl69518bc2011-04-16 16:44:54 +0200870command line. The ``default`` keyword argument of :meth:`add_argument`, whose
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000871value defaults to ``None``, specifies what value should be used if the
872command-line arg is not present. For optional arguments, the ``default`` value
873is used when the option string was not present at the command line::
874
875 >>> parser = argparse.ArgumentParser()
876 >>> parser.add_argument('--foo', default=42)
877 >>> parser.parse_args('--foo 2'.split())
878 Namespace(foo='2')
879 >>> parser.parse_args(''.split())
880 Namespace(foo=42)
881
882For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
883is used when no command-line arg was present::
884
885 >>> parser = argparse.ArgumentParser()
886 >>> parser.add_argument('foo', nargs='?', default=42)
887 >>> parser.parse_args('a'.split())
888 Namespace(foo='a')
889 >>> parser.parse_args(''.split())
890 Namespace(foo=42)
891
892
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000893Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
894command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000895
896 >>> parser = argparse.ArgumentParser()
897 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
898 >>> parser.parse_args([])
899 Namespace()
900 >>> parser.parse_args(['--foo', '1'])
901 Namespace(foo='1')
902
903
904type
905^^^^
906
907By default, ArgumentParser objects read command-line args in as simple strings.
908However, quite often the command-line string should instead be interpreted as
Georg Brandl04536b02011-01-09 09:31:01 +0000909another type, like a :class:`float` or :class:`int`. The ``type`` keyword
910argument of :meth:`add_argument` allows any necessary type-checking and
911type-conversions to be performed. Common built-in types and functions can be
912used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000913
914 >>> parser = argparse.ArgumentParser()
915 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000916 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000917 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000918 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000919
920To ease the use of various types of files, the argparse module provides the
921factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000922:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000923writable file::
924
925 >>> parser = argparse.ArgumentParser()
926 >>> parser.add_argument('bar', type=argparse.FileType('w'))
927 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000928 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000929
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000930``type=`` can take any callable that takes a single string argument and returns
931the type-converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000932
933 >>> def perfect_square(string):
934 ... value = int(string)
935 ... sqrt = math.sqrt(value)
936 ... if sqrt != int(sqrt):
937 ... msg = "%r is not a perfect square" % string
938 ... raise argparse.ArgumentTypeError(msg)
939 ... return value
940 ...
941 >>> parser = argparse.ArgumentParser(prog='PROG')
942 >>> parser.add_argument('foo', type=perfect_square)
943 >>> parser.parse_args('9'.split())
944 Namespace(foo=9)
945 >>> parser.parse_args('7'.split())
946 usage: PROG [-h] foo
947 PROG: error: argument foo: '7' is not a perfect square
948
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000949The choices_ keyword argument may be more convenient for type checkers that
950simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000951
952 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +0000953 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000954 >>> parser.parse_args('7'.split())
955 Namespace(foo=7)
956 >>> parser.parse_args('11'.split())
957 usage: PROG [-h] {5,6,7,8,9}
958 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
959
960See the choices_ section for more details.
961
962
963choices
964^^^^^^^
965
966Some command-line args should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000967These can be handled by passing a container object as the ``choices`` keyword
Georg Brandl69518bc2011-04-16 16:44:54 +0200968argument to :meth:`add_argument`. When the command line is parsed, arg values
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000969will be checked, and an error message will be displayed if the arg was not one
970of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000971
972 >>> parser = argparse.ArgumentParser(prog='PROG')
973 >>> parser.add_argument('foo', choices='abc')
974 >>> parser.parse_args('c'.split())
975 Namespace(foo='c')
976 >>> parser.parse_args('X'.split())
977 usage: PROG [-h] {a,b,c}
978 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
979
980Note that inclusion in the ``choices`` container is checked after any type_
981conversions have been performed, so the type of the objects in the ``choices``
982container should match the type_ specified::
983
984 >>> parser = argparse.ArgumentParser(prog='PROG')
985 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
986 >>> parser.parse_args('1j'.split())
987 Namespace(foo=1j)
988 >>> parser.parse_args('-- -4'.split())
989 usage: PROG [-h] {1,1j}
990 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
991
992Any object that supports the ``in`` operator can be passed as the ``choices``
993value, so :class:`dict` objects, :class:`set` objects, custom containers,
994etc. are all supported.
995
996
997required
998^^^^^^^^
999
1000In general, the argparse module assumes that flags like ``-f`` and ``--bar``
Georg Brandl69518bc2011-04-16 16:44:54 +02001001indicate *optional* arguments, which can always be omitted at the command line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001002To make an option *required*, ``True`` can be specified for the ``required=``
1003keyword argument to :meth:`add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001004
1005 >>> parser = argparse.ArgumentParser()
1006 >>> parser.add_argument('--foo', required=True)
1007 >>> parser.parse_args(['--foo', 'BAR'])
1008 Namespace(foo='BAR')
1009 >>> parser.parse_args([])
1010 usage: argparse.py [-h] [--foo FOO]
1011 argparse.py: error: option --foo is required
1012
1013As the example shows, if an option is marked as ``required``, :meth:`parse_args`
1014will report an error if that option is not present at the command line.
1015
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001016.. note::
1017
1018 Required options are generally considered bad form because users expect
1019 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001020
1021
1022help
1023^^^^
1024
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001025The ``help`` value is a string containing a brief description of the argument.
1026When a user requests help (usually by using ``-h`` or ``--help`` at the
Georg Brandl69518bc2011-04-16 16:44:54 +02001027command line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001028argument::
1029
1030 >>> parser = argparse.ArgumentParser(prog='frobble')
1031 >>> parser.add_argument('--foo', action='store_true',
1032 ... help='foo the bars before frobbling')
1033 >>> parser.add_argument('bar', nargs='+',
1034 ... help='one of the bars to be frobbled')
1035 >>> parser.parse_args('-h'.split())
1036 usage: frobble [-h] [--foo] bar [bar ...]
1037
1038 positional arguments:
1039 bar one of the bars to be frobbled
1040
1041 optional arguments:
1042 -h, --help show this help message and exit
1043 --foo foo the bars before frobbling
1044
1045The ``help`` strings can include various format specifiers to avoid repetition
1046of things like the program name or the argument default_. The available
1047specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1048:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1049
1050 >>> parser = argparse.ArgumentParser(prog='frobble')
1051 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1052 ... help='the bar to %(prog)s (default: %(default)s)')
1053 >>> parser.print_help()
1054 usage: frobble [-h] [bar]
1055
1056 positional arguments:
1057 bar the bar to frobble (default: 42)
1058
1059 optional arguments:
1060 -h, --help show this help message and exit
1061
1062
1063metavar
1064^^^^^^^
1065
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001066When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001067to each expected argument. By default, ArgumentParser objects use the dest_
1068value as the "name" of each object. By default, for positional argument
1069actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001070the dest_ value is uppercased. So, a single positional argument with
1071``dest='bar'`` will that argument will be referred to as ``bar``. A single
1072optional argument ``--foo`` that should be followed by a single command-line arg
1073will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001074
1075 >>> parser = argparse.ArgumentParser()
1076 >>> parser.add_argument('--foo')
1077 >>> parser.add_argument('bar')
1078 >>> parser.parse_args('X --foo Y'.split())
1079 Namespace(bar='X', foo='Y')
1080 >>> parser.print_help()
1081 usage: [-h] [--foo FOO] bar
1082
1083 positional arguments:
1084 bar
1085
1086 optional arguments:
1087 -h, --help show this help message and exit
1088 --foo FOO
1089
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001090An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001091
1092 >>> parser = argparse.ArgumentParser()
1093 >>> parser.add_argument('--foo', metavar='YYY')
1094 >>> parser.add_argument('bar', metavar='XXX')
1095 >>> parser.parse_args('X --foo Y'.split())
1096 Namespace(bar='X', foo='Y')
1097 >>> parser.print_help()
1098 usage: [-h] [--foo YYY] XXX
1099
1100 positional arguments:
1101 XXX
1102
1103 optional arguments:
1104 -h, --help show this help message and exit
1105 --foo YYY
1106
1107Note that ``metavar`` only changes the *displayed* name - the name of the
1108attribute on the :meth:`parse_args` object is still determined by the dest_
1109value.
1110
1111Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001112Providing a tuple to ``metavar`` specifies a different display for each of the
1113arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001114
1115 >>> parser = argparse.ArgumentParser(prog='PROG')
1116 >>> parser.add_argument('-x', nargs=2)
1117 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1118 >>> parser.print_help()
1119 usage: PROG [-h] [-x X X] [--foo bar baz]
1120
1121 optional arguments:
1122 -h, --help show this help message and exit
1123 -x X X
1124 --foo bar baz
1125
1126
1127dest
1128^^^^
1129
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001130Most :class:`ArgumentParser` actions add some value as an attribute of the
1131object returned by :meth:`parse_args`. The name of this attribute is determined
1132by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1133argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001134:meth:`add_argument`::
1135
1136 >>> parser = argparse.ArgumentParser()
1137 >>> parser.add_argument('bar')
1138 >>> parser.parse_args('XXX'.split())
1139 Namespace(bar='XXX')
1140
1141For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001142the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001143taking the first long option string and stripping away the initial ``'--'``
1144string. If no long option strings were supplied, ``dest`` will be derived from
1145the first short option string by stripping the initial ``'-'`` character. Any
1146internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1147the string is a valid attribute name. The examples below illustrate this
1148behavior::
1149
1150 >>> parser = argparse.ArgumentParser()
1151 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1152 >>> parser.add_argument('-x', '-y')
1153 >>> parser.parse_args('-f 1 -x 2'.split())
1154 Namespace(foo_bar='1', x='2')
1155 >>> parser.parse_args('--foo 1 -y 2'.split())
1156 Namespace(foo_bar='1', x='2')
1157
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001158``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001159
1160 >>> parser = argparse.ArgumentParser()
1161 >>> parser.add_argument('--foo', dest='bar')
1162 >>> parser.parse_args('--foo XXX'.split())
1163 Namespace(bar='XXX')
1164
1165
1166The parse_args() method
1167-----------------------
1168
Georg Brandle0bf91d2010-10-17 10:34:28 +00001169.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001170
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001171 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001172 namespace. Return the populated namespace.
1173
1174 Previous calls to :meth:`add_argument` determine exactly what objects are
1175 created and how they are assigned. See the documentation for
1176 :meth:`add_argument` for details.
1177
1178 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001179 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001180
Georg Brandle0bf91d2010-10-17 10:34:28 +00001181
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001182Option value syntax
1183^^^^^^^^^^^^^^^^^^^
1184
1185The :meth:`parse_args` method supports several ways of specifying the value of
1186an option (if it takes one). In the simplest case, the option and its value are
1187passed as two separate arguments::
1188
1189 >>> parser = argparse.ArgumentParser(prog='PROG')
1190 >>> parser.add_argument('-x')
1191 >>> parser.add_argument('--foo')
1192 >>> parser.parse_args('-x X'.split())
1193 Namespace(foo=None, x='X')
1194 >>> parser.parse_args('--foo FOO'.split())
1195 Namespace(foo='FOO', x=None)
1196
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001197For long options (options with names longer than a single character), the option
Georg Brandl69518bc2011-04-16 16:44:54 +02001198and value can also be passed as a single command-line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001199separate them::
1200
1201 >>> parser.parse_args('--foo=FOO'.split())
1202 Namespace(foo='FOO', x=None)
1203
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001204For short options (options only one character long), the option and its value
1205can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001206
1207 >>> parser.parse_args('-xX'.split())
1208 Namespace(foo=None, x='X')
1209
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001210Several short options can be joined together, using only a single ``-`` prefix,
1211as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001212
1213 >>> parser = argparse.ArgumentParser(prog='PROG')
1214 >>> parser.add_argument('-x', action='store_true')
1215 >>> parser.add_argument('-y', action='store_true')
1216 >>> parser.add_argument('-z')
1217 >>> parser.parse_args('-xyzZ'.split())
1218 Namespace(x=True, y=True, z='Z')
1219
1220
1221Invalid arguments
1222^^^^^^^^^^^^^^^^^
1223
Georg Brandl69518bc2011-04-16 16:44:54 +02001224While parsing the command line, ``parse_args`` checks for a variety of errors,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001225including ambiguous options, invalid types, invalid options, wrong number of
1226positional arguments, etc. When it encounters such an error, it exits and
1227prints the error along with a usage message::
1228
1229 >>> parser = argparse.ArgumentParser(prog='PROG')
1230 >>> parser.add_argument('--foo', type=int)
1231 >>> parser.add_argument('bar', nargs='?')
1232
1233 >>> # invalid type
1234 >>> parser.parse_args(['--foo', 'spam'])
1235 usage: PROG [-h] [--foo FOO] [bar]
1236 PROG: error: argument --foo: invalid int value: 'spam'
1237
1238 >>> # invalid option
1239 >>> parser.parse_args(['--bar'])
1240 usage: PROG [-h] [--foo FOO] [bar]
1241 PROG: error: no such option: --bar
1242
1243 >>> # wrong number of arguments
1244 >>> parser.parse_args(['spam', 'badger'])
1245 usage: PROG [-h] [--foo FOO] [bar]
1246 PROG: error: extra arguments found: badger
1247
1248
1249Arguments containing ``"-"``
1250^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1251
1252The ``parse_args`` method attempts to give errors whenever the user has clearly
1253made a mistake, but some situations are inherently ambiguous. For example, the
1254command-line arg ``'-1'`` could either be an attempt to specify an option or an
1255attempt to provide a positional argument. The ``parse_args`` method is cautious
1256here: positional arguments may only begin with ``'-'`` if they look like
1257negative numbers and there are no options in the parser that look like negative
1258numbers::
1259
1260 >>> parser = argparse.ArgumentParser(prog='PROG')
1261 >>> parser.add_argument('-x')
1262 >>> parser.add_argument('foo', nargs='?')
1263
1264 >>> # no negative number options, so -1 is a positional argument
1265 >>> parser.parse_args(['-x', '-1'])
1266 Namespace(foo=None, x='-1')
1267
1268 >>> # no negative number options, so -1 and -5 are positional arguments
1269 >>> parser.parse_args(['-x', '-1', '-5'])
1270 Namespace(foo='-5', x='-1')
1271
1272 >>> parser = argparse.ArgumentParser(prog='PROG')
1273 >>> parser.add_argument('-1', dest='one')
1274 >>> parser.add_argument('foo', nargs='?')
1275
1276 >>> # negative number options present, so -1 is an option
1277 >>> parser.parse_args(['-1', 'X'])
1278 Namespace(foo=None, one='X')
1279
1280 >>> # negative number options present, so -2 is an option
1281 >>> parser.parse_args(['-2'])
1282 usage: PROG [-h] [-1 ONE] [foo]
1283 PROG: error: no such option: -2
1284
1285 >>> # negative number options present, so both -1s are options
1286 >>> parser.parse_args(['-1', '-1'])
1287 usage: PROG [-h] [-1 ONE] [foo]
1288 PROG: error: argument -1: expected one argument
1289
1290If you have positional arguments that must begin with ``'-'`` and don't look
1291like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1292``parse_args`` that everything after that is a positional argument::
1293
1294 >>> parser.parse_args(['--', '-f'])
1295 Namespace(foo='-f', one=None)
1296
1297
1298Argument abbreviations
1299^^^^^^^^^^^^^^^^^^^^^^
1300
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001301The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001302abbreviation is unambiguous::
1303
1304 >>> parser = argparse.ArgumentParser(prog='PROG')
1305 >>> parser.add_argument('-bacon')
1306 >>> parser.add_argument('-badger')
1307 >>> parser.parse_args('-bac MMM'.split())
1308 Namespace(bacon='MMM', badger=None)
1309 >>> parser.parse_args('-bad WOOD'.split())
1310 Namespace(bacon=None, badger='WOOD')
1311 >>> parser.parse_args('-ba BA'.split())
1312 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1313 PROG: error: ambiguous option: -ba could match -badger, -bacon
1314
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001315An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001316
1317
1318Beyond ``sys.argv``
1319^^^^^^^^^^^^^^^^^^^
1320
1321Sometimes it may be useful to have an ArgumentParser parse args other than those
1322of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001323``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001324
1325 >>> parser = argparse.ArgumentParser()
1326 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001327 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001328 ... nargs='+', help='an integer in the range 0..9')
1329 >>> parser.add_argument(
1330 ... '--sum', dest='accumulate', action='store_const', const=sum,
1331 ... default=max, help='sum the integers (default: find the max)')
1332 >>> parser.parse_args(['1', '2', '3', '4'])
1333 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1334 >>> parser.parse_args('1 2 3 4 --sum'.split())
1335 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1336
1337
Steven Bethardd8f2d502011-03-26 19:50:06 +01001338The Namespace object
1339^^^^^^^^^^^^^^^^^^^^
1340
1341By default, :meth:`parse_args` will return a new object of type :class:`Namespace`
1342where the necessary attributes have been set. This class is deliberately simple,
1343just an :class:`object` subclass with a readable string representation. If you
1344prefer to have dict-like view of the attributes, you can use the standard Python
1345idiom via :func:`vars`::
1346
1347 >>> parser = argparse.ArgumentParser()
1348 >>> parser.add_argument('--foo')
1349 >>> args = parser.parse_args(['--foo', 'BAR'])
1350 >>> vars(args)
1351 {'foo': 'BAR'}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001352
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001353It may also be useful to have an :class:`ArgumentParser` assign attributes to an
Steven Bethardd8f2d502011-03-26 19:50:06 +01001354already existing object, rather than a new :class:`Namespace` object. This can
1355be achieved by specifying the ``namespace=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001356
Éric Araujo28053fb2010-11-22 03:09:19 +00001357 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001358 ... pass
1359 ...
1360 >>> c = C()
1361 >>> parser = argparse.ArgumentParser()
1362 >>> parser.add_argument('--foo')
1363 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1364 >>> c.foo
1365 'BAR'
1366
1367
1368Other utilities
1369---------------
1370
1371Sub-commands
1372^^^^^^^^^^^^
1373
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001374.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001375
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001376 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001377 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001378 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001379 this way can be a particularly good idea when a program performs several
1380 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001381 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001382 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1383 called with no arguments and returns an special action object. This object
1384 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001385 :class:`ArgumentParser` constructor arguments, and returns an
1386 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001387
1388 Some example usage::
1389
1390 >>> # create the top-level parser
1391 >>> parser = argparse.ArgumentParser(prog='PROG')
1392 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1393 >>> subparsers = parser.add_subparsers(help='sub-command help')
1394 >>>
1395 >>> # create the parser for the "a" command
1396 >>> parser_a = subparsers.add_parser('a', help='a help')
1397 >>> parser_a.add_argument('bar', type=int, help='bar help')
1398 >>>
1399 >>> # create the parser for the "b" command
1400 >>> parser_b = subparsers.add_parser('b', help='b help')
1401 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1402 >>>
1403 >>> # parse some arg lists
1404 >>> parser.parse_args(['a', '12'])
1405 Namespace(bar=12, foo=False)
1406 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1407 Namespace(baz='Z', foo=True)
1408
1409 Note that the object returned by :meth:`parse_args` will only contain
1410 attributes for the main parser and the subparser that was selected by the
1411 command line (and not any other subparsers). So in the example above, when
1412 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1413 present, and when the ``"b"`` command is specified, only the ``foo`` and
1414 ``baz`` attributes are present.
1415
1416 Similarly, when a help message is requested from a subparser, only the help
1417 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001418 include parent parser or sibling parser messages. (A help message for each
1419 subparser command, however, can be given by supplying the ``help=`` argument
1420 to ``add_parser`` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001421
1422 ::
1423
1424 >>> parser.parse_args(['--help'])
1425 usage: PROG [-h] [--foo] {a,b} ...
1426
1427 positional arguments:
1428 {a,b} sub-command help
1429 a a help
1430 b b help
1431
1432 optional arguments:
1433 -h, --help show this help message and exit
1434 --foo foo help
1435
1436 >>> parser.parse_args(['a', '--help'])
1437 usage: PROG a [-h] bar
1438
1439 positional arguments:
1440 bar bar help
1441
1442 optional arguments:
1443 -h, --help show this help message and exit
1444
1445 >>> parser.parse_args(['b', '--help'])
1446 usage: PROG b [-h] [--baz {X,Y,Z}]
1447
1448 optional arguments:
1449 -h, --help show this help message and exit
1450 --baz {X,Y,Z} baz help
1451
1452 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1453 keyword arguments. When either is present, the subparser's commands will
1454 appear in their own group in the help output. For example::
1455
1456 >>> parser = argparse.ArgumentParser()
1457 >>> subparsers = parser.add_subparsers(title='subcommands',
1458 ... description='valid subcommands',
1459 ... help='additional help')
1460 >>> subparsers.add_parser('foo')
1461 >>> subparsers.add_parser('bar')
1462 >>> parser.parse_args(['-h'])
1463 usage: [-h] {foo,bar} ...
1464
1465 optional arguments:
1466 -h, --help show this help message and exit
1467
1468 subcommands:
1469 valid subcommands
1470
1471 {foo,bar} additional help
1472
Steven Bethardfd311a72010-12-18 11:19:23 +00001473 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1474 which allows multiple strings to refer to the same subparser. This example,
1475 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1476
1477 >>> parser = argparse.ArgumentParser()
1478 >>> subparsers = parser.add_subparsers()
1479 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1480 >>> checkout.add_argument('foo')
1481 >>> parser.parse_args(['co', 'bar'])
1482 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001483
1484 One particularly effective way of handling sub-commands is to combine the use
1485 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1486 that each subparser knows which Python function it should execute. For
1487 example::
1488
1489 >>> # sub-command functions
1490 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001491 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001492 ...
1493 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001494 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001495 ...
1496 >>> # create the top-level parser
1497 >>> parser = argparse.ArgumentParser()
1498 >>> subparsers = parser.add_subparsers()
1499 >>>
1500 >>> # create the parser for the "foo" command
1501 >>> parser_foo = subparsers.add_parser('foo')
1502 >>> parser_foo.add_argument('-x', type=int, default=1)
1503 >>> parser_foo.add_argument('y', type=float)
1504 >>> parser_foo.set_defaults(func=foo)
1505 >>>
1506 >>> # create the parser for the "bar" command
1507 >>> parser_bar = subparsers.add_parser('bar')
1508 >>> parser_bar.add_argument('z')
1509 >>> parser_bar.set_defaults(func=bar)
1510 >>>
1511 >>> # parse the args and call whatever function was selected
1512 >>> args = parser.parse_args('foo 1 -x 2'.split())
1513 >>> args.func(args)
1514 2.0
1515 >>>
1516 >>> # parse the args and call whatever function was selected
1517 >>> args = parser.parse_args('bar XYZYX'.split())
1518 >>> args.func(args)
1519 ((XYZYX))
1520
Steven Bethardfd311a72010-12-18 11:19:23 +00001521 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001522 appropriate function after argument parsing is complete. Associating
1523 functions with actions like this is typically the easiest way to handle the
1524 different actions for each of your subparsers. However, if it is necessary
1525 to check the name of the subparser that was invoked, the ``dest`` keyword
1526 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001527
1528 >>> parser = argparse.ArgumentParser()
1529 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1530 >>> subparser1 = subparsers.add_parser('1')
1531 >>> subparser1.add_argument('-x')
1532 >>> subparser2 = subparsers.add_parser('2')
1533 >>> subparser2.add_argument('y')
1534 >>> parser.parse_args(['2', 'frobble'])
1535 Namespace(subparser_name='2', y='frobble')
1536
1537
1538FileType objects
1539^^^^^^^^^^^^^^^^
1540
1541.. class:: FileType(mode='r', bufsize=None)
1542
1543 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001544 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1545 :class:`FileType` objects as their type will open command-line args as files
1546 with the requested modes and buffer sizes:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001547
1548 >>> parser = argparse.ArgumentParser()
1549 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1550 >>> parser.parse_args(['--output', 'out'])
Georg Brandl04536b02011-01-09 09:31:01 +00001551 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001552
1553 FileType objects understand the pseudo-argument ``'-'`` and automatically
1554 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1555 ``sys.stdout`` for writable :class:`FileType` objects:
1556
1557 >>> parser = argparse.ArgumentParser()
1558 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1559 >>> parser.parse_args(['-'])
Georg Brandl04536b02011-01-09 09:31:01 +00001560 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001561
1562
1563Argument groups
1564^^^^^^^^^^^^^^^
1565
Georg Brandle0bf91d2010-10-17 10:34:28 +00001566.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001567
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001568 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001569 "positional arguments" and "optional arguments" when displaying help
1570 messages. When there is a better conceptual grouping of arguments than this
1571 default one, appropriate groups can be created using the
1572 :meth:`add_argument_group` method::
1573
1574 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1575 >>> group = parser.add_argument_group('group')
1576 >>> group.add_argument('--foo', help='foo help')
1577 >>> group.add_argument('bar', help='bar help')
1578 >>> parser.print_help()
1579 usage: PROG [--foo FOO] bar
1580
1581 group:
1582 bar bar help
1583 --foo FOO foo help
1584
1585 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001586 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1587 :class:`ArgumentParser`. When an argument is added to the group, the parser
1588 treats it just like a normal argument, but displays the argument in a
1589 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001590 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001591 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001592
1593 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1594 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1595 >>> group1.add_argument('foo', help='foo help')
1596 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1597 >>> group2.add_argument('--bar', help='bar help')
1598 >>> parser.print_help()
1599 usage: PROG [--bar BAR] foo
1600
1601 group1:
1602 group1 description
1603
1604 foo foo help
1605
1606 group2:
1607 group2 description
1608
1609 --bar BAR bar help
1610
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001611 Note that any arguments not your user defined groups will end up back in the
1612 usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001613
1614
1615Mutual exclusion
1616^^^^^^^^^^^^^^^^
1617
Georg Brandle0bf91d2010-10-17 10:34:28 +00001618.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001619
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001620 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001621 the arguments in the mutually exclusive group was present on the command
1622 line::
1623
1624 >>> parser = argparse.ArgumentParser(prog='PROG')
1625 >>> group = parser.add_mutually_exclusive_group()
1626 >>> group.add_argument('--foo', action='store_true')
1627 >>> group.add_argument('--bar', action='store_false')
1628 >>> parser.parse_args(['--foo'])
1629 Namespace(bar=True, foo=True)
1630 >>> parser.parse_args(['--bar'])
1631 Namespace(bar=False, foo=False)
1632 >>> parser.parse_args(['--foo', '--bar'])
1633 usage: PROG [-h] [--foo | --bar]
1634 PROG: error: argument --bar: not allowed with argument --foo
1635
Georg Brandle0bf91d2010-10-17 10:34:28 +00001636 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001637 argument, to indicate that at least one of the mutually exclusive arguments
1638 is required::
1639
1640 >>> parser = argparse.ArgumentParser(prog='PROG')
1641 >>> group = parser.add_mutually_exclusive_group(required=True)
1642 >>> group.add_argument('--foo', action='store_true')
1643 >>> group.add_argument('--bar', action='store_false')
1644 >>> parser.parse_args([])
1645 usage: PROG [-h] (--foo | --bar)
1646 PROG: error: one of the arguments --foo --bar is required
1647
1648 Note that currently mutually exclusive argument groups do not support the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001649 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001650
1651
1652Parser defaults
1653^^^^^^^^^^^^^^^
1654
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001655.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001656
1657 Most of the time, the attributes of the object returned by :meth:`parse_args`
1658 will be fully determined by inspecting the command-line args and the argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001659 actions. :meth:`ArgumentParser.set_defaults` allows some additional
Georg Brandl69518bc2011-04-16 16:44:54 +02001660 attributes that are determined without any inspection of the command line to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001661 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001662
1663 >>> parser = argparse.ArgumentParser()
1664 >>> parser.add_argument('foo', type=int)
1665 >>> parser.set_defaults(bar=42, baz='badger')
1666 >>> parser.parse_args(['736'])
1667 Namespace(bar=42, baz='badger', foo=736)
1668
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001669 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001670
1671 >>> parser = argparse.ArgumentParser()
1672 >>> parser.add_argument('--foo', default='bar')
1673 >>> parser.set_defaults(foo='spam')
1674 >>> parser.parse_args([])
1675 Namespace(foo='spam')
1676
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001677 Parser-level defaults can be particularly useful when working with multiple
1678 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1679 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001680
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001681.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001682
1683 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001684 :meth:`~ArgumentParser.add_argument` or by
1685 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001686
1687 >>> parser = argparse.ArgumentParser()
1688 >>> parser.add_argument('--foo', default='badger')
1689 >>> parser.get_default('foo')
1690 'badger'
1691
1692
1693Printing help
1694^^^^^^^^^^^^^
1695
1696In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001697and printing any usage or error messages. However, several formatting methods
1698are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001699
Georg Brandle0bf91d2010-10-17 10:34:28 +00001700.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001701
1702 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001703 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001704 assumed.
1705
Georg Brandle0bf91d2010-10-17 10:34:28 +00001706.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001707
1708 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001709 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001710 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001711
1712There are also variants of these methods that simply return a string instead of
1713printing it:
1714
Georg Brandle0bf91d2010-10-17 10:34:28 +00001715.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001716
1717 Return a string containing a brief description of how the
1718 :class:`ArgumentParser` should be invoked on the command line.
1719
Georg Brandle0bf91d2010-10-17 10:34:28 +00001720.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001721
1722 Return a string containing a help message, including the program usage and
1723 information about the arguments registered with the :class:`ArgumentParser`.
1724
1725
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001726Partial parsing
1727^^^^^^^^^^^^^^^
1728
Georg Brandle0bf91d2010-10-17 10:34:28 +00001729.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001730
Georg Brandl69518bc2011-04-16 16:44:54 +02001731Sometimes a script may only parse a few of the command-line arguments, passing
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001732the remaining arguments on to another script or program. In these cases, the
1733:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001734:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1735extra arguments are present. Instead, it returns a two item tuple containing
1736the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001737
1738::
1739
1740 >>> parser = argparse.ArgumentParser()
1741 >>> parser.add_argument('--foo', action='store_true')
1742 >>> parser.add_argument('bar')
1743 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1744 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1745
1746
1747Customizing file parsing
1748^^^^^^^^^^^^^^^^^^^^^^^^
1749
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001750.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001751
Georg Brandle0bf91d2010-10-17 10:34:28 +00001752 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001753 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001754 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1755 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001756
Georg Brandle0bf91d2010-10-17 10:34:28 +00001757 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001758 the argument file. It returns a list of arguments parsed from this string.
1759 The method is called once per line read from the argument file, in order.
1760
1761 A useful override of this method is one that treats each space-separated word
1762 as an argument::
1763
1764 def convert_arg_line_to_args(self, arg_line):
1765 for arg in arg_line.split():
1766 if not arg.strip():
1767 continue
1768 yield arg
1769
1770
Georg Brandl93754922010-10-17 10:28:04 +00001771Exiting methods
1772^^^^^^^^^^^^^^^
1773
1774.. method:: ArgumentParser.exit(status=0, message=None)
1775
1776 This method terminates the program, exiting with the specified *status*
1777 and, if given, it prints a *message* before that.
1778
1779.. method:: ArgumentParser.error(message)
1780
1781 This method prints a usage message including the *message* to the
1782 standard output and terminates the program with a status code of 2.
1783
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001784.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001785
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001786Upgrading optparse code
1787-----------------------
1788
1789Originally, the argparse module had attempted to maintain compatibility with
1790optparse. However, optparse was difficult to extend transparently, particularly
1791with the changes required to support the new ``nargs=`` specifiers and better
Georg Brandl386bc6d2010-04-25 10:19:53 +00001792usage messages. When most everything in optparse had either been copy-pasted
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001793over or monkey-patched, it no longer seemed practical to try to maintain the
1794backwards compatibility.
1795
1796A partial upgrade path from optparse to argparse:
1797
Georg Brandlc9007082011-01-09 09:04:08 +00001798* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
1799 calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001800
1801* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001802 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1803 calls for the positional arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001804
1805* Replace callback actions and the ``callback_*`` keyword arguments with
1806 ``type`` or ``action`` arguments.
1807
1808* Replace string names for ``type`` keyword arguments with the corresponding
1809 type objects (e.g. int, float, complex, etc).
1810
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001811* Replace :class:`optparse.Values` with :class:`Namespace` and
1812 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1813 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001814
1815* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1816 the standard python syntax to use dictionaries to format strings, that is,
1817 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001818
1819* Replace the OptionParser constructor ``version`` argument with a call to
1820 ``parser.add_argument('--version', action='version', version='<the version>')``