blob: 7a89654c797eb62b6b97f09003a34fc7c2a5fa2c [file] [log] [blame]
Georg Brandle0bf91d2010-10-17 10:34:28 +00001:mod:`argparse` --- Parser for command line options, arguments and sub-commands
2===============================================================================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4.. module:: argparse
5 :synopsis: Command-line option and argument parsing library.
6.. 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
15The :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
111: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
114attributes parsed out of the command-line::
115
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
224If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser
225help 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
354
355formatter_class
356^^^^^^^^^^^^^^^
357
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000358:class:`ArgumentParser` objects allow the help formatting to be customized by
Steven Bethard0331e902011-03-26 14:48:04 +0100359specifying an alternate formatting class.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000360
Steven Bethard0331e902011-03-26 14:48:04 +0100361:class:`RawDescriptionHelpFormatter` and :class:`RawTextHelpFormatter` give
362more control over how textual descriptions are displayed.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000363By default, :class:`ArgumentParser` objects line-wrap the description_ and
364epilog_ texts in command-line help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000365
366 >>> parser = argparse.ArgumentParser(
367 ... prog='PROG',
368 ... description='''this description
369 ... was indented weird
370 ... but that is okay''',
371 ... epilog='''
372 ... likewise for this epilog whose whitespace will
373 ... be cleaned up and whose words will be wrapped
374 ... across a couple lines''')
375 >>> parser.print_help()
376 usage: PROG [-h]
377
378 this description was indented weird but that is okay
379
380 optional arguments:
381 -h, --help show this help message and exit
382
383 likewise for this epilog whose whitespace will be cleaned up and whose words
384 will be wrapped across a couple lines
385
Steven Bethard0331e902011-03-26 14:48:04 +0100386Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000387indicates that description_ and epilog_ are already correctly formatted and
388should not be line-wrapped::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000389
390 >>> parser = argparse.ArgumentParser(
391 ... prog='PROG',
392 ... formatter_class=argparse.RawDescriptionHelpFormatter,
393 ... description=textwrap.dedent('''\
394 ... Please do not mess up this text!
395 ... --------------------------------
396 ... I have indented it
397 ... exactly the way
398 ... I want it
399 ... '''))
400 >>> parser.print_help()
401 usage: PROG [-h]
402
403 Please do not mess up this text!
404 --------------------------------
405 I have indented it
406 exactly the way
407 I want it
408
409 optional arguments:
410 -h, --help show this help message and exit
411
Steven Bethard0331e902011-03-26 14:48:04 +0100412:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000413including argument descriptions.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000414
Steven Bethard0331e902011-03-26 14:48:04 +0100415:class:`ArgumentDefaultsHelpFormatter` automatically adds information about
416default values to each of the argument help messages::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000417
418 >>> parser = argparse.ArgumentParser(
419 ... prog='PROG',
420 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
421 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
422 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
423 >>> parser.print_help()
424 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
425
426 positional arguments:
427 bar BAR! (default: [1, 2, 3])
428
429 optional arguments:
430 -h, --help show this help message and exit
431 --foo FOO FOO! (default: 42)
432
Steven Bethard0331e902011-03-26 14:48:04 +0100433:class:`MetavarTypeHelpFormatter` uses the name of the type_ argument for each
434argument as as the display name for its values (rather than using the dest_
435as the regular formatter does)::
436
437 >>> parser = argparse.ArgumentParser(
438 ... prog='PROG',
439 ... formatter_class=argparse.MetavarTypeHelpFormatter)
440 >>> parser.add_argument('--foo', type=int)
441 >>> parser.add_argument('bar', type=float)
442 >>> parser.print_help()
443 usage: PROG [-h] [--foo int] float
444
445 positional arguments:
446 float
447
448 optional arguments:
449 -h, --help show this help message and exit
450 --foo int
451
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000452
453conflict_handler
454^^^^^^^^^^^^^^^^
455
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000456:class:`ArgumentParser` objects do not allow two actions with the same option
457string. By default, :class:`ArgumentParser` objects raises an exception if an
458attempt is made to create an argument with an option string that is already in
459use::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000460
461 >>> parser = argparse.ArgumentParser(prog='PROG')
462 >>> parser.add_argument('-f', '--foo', help='old foo help')
463 >>> parser.add_argument('--foo', help='new foo help')
464 Traceback (most recent call last):
465 ..
466 ArgumentError: argument --foo: conflicting option string(s): --foo
467
468Sometimes (e.g. when using parents_) it may be useful to simply override any
469older arguments with the same option string. To get this behavior, the value
470``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000471:class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000472
473 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
474 >>> parser.add_argument('-f', '--foo', help='old foo help')
475 >>> parser.add_argument('--foo', help='new foo help')
476 >>> parser.print_help()
477 usage: PROG [-h] [-f FOO] [--foo FOO]
478
479 optional arguments:
480 -h, --help show this help message and exit
481 -f FOO old foo help
482 --foo FOO new foo help
483
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000484Note that :class:`ArgumentParser` objects only remove an action if all of its
485option strings are overridden. So, in the example above, the old ``-f/--foo``
486action is retained as the ``-f`` action, because only the ``--foo`` option
487string was overridden.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000488
489
490prog
491^^^^
492
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000493By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
494how to display the name of the program in help messages. This default is almost
Ezio Melottif82340d2010-05-27 22:38:16 +0000495always desirable because it will make the help messages match how the program was
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000496invoked on the command line. For example, consider a file named
497``myprogram.py`` with the following code::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000498
499 import argparse
500 parser = argparse.ArgumentParser()
501 parser.add_argument('--foo', help='foo help')
502 args = parser.parse_args()
503
504The help for this program will display ``myprogram.py`` as the program name
505(regardless of where the program was invoked from)::
506
507 $ python myprogram.py --help
508 usage: myprogram.py [-h] [--foo FOO]
509
510 optional arguments:
511 -h, --help show this help message and exit
512 --foo FOO foo help
513 $ cd ..
514 $ python subdir\myprogram.py --help
515 usage: myprogram.py [-h] [--foo FOO]
516
517 optional arguments:
518 -h, --help show this help message and exit
519 --foo FOO foo help
520
521To change this default behavior, another value can be supplied using the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000522``prog=`` argument to :class:`ArgumentParser`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000523
524 >>> parser = argparse.ArgumentParser(prog='myprogram')
525 >>> parser.print_help()
526 usage: myprogram [-h]
527
528 optional arguments:
529 -h, --help show this help message and exit
530
531Note that the program name, whether determined from ``sys.argv[0]`` or from the
532``prog=`` argument, is available to help messages using the ``%(prog)s`` format
533specifier.
534
535::
536
537 >>> parser = argparse.ArgumentParser(prog='myprogram')
538 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
539 >>> parser.print_help()
540 usage: myprogram [-h] [--foo FOO]
541
542 optional arguments:
543 -h, --help show this help message and exit
544 --foo FOO foo of the myprogram program
545
546
547usage
548^^^^^
549
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000550By default, :class:`ArgumentParser` calculates the usage message from the
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000551arguments it contains::
552
553 >>> parser = argparse.ArgumentParser(prog='PROG')
554 >>> parser.add_argument('--foo', nargs='?', help='foo help')
555 >>> parser.add_argument('bar', nargs='+', help='bar help')
556 >>> parser.print_help()
557 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
558
559 positional arguments:
560 bar bar help
561
562 optional arguments:
563 -h, --help show this help message and exit
564 --foo [FOO] foo help
565
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000566The default message can be overridden with the ``usage=`` keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000567
568 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
569 >>> parser.add_argument('--foo', nargs='?', help='foo help')
570 >>> parser.add_argument('bar', nargs='+', help='bar help')
571 >>> parser.print_help()
572 usage: PROG [options]
573
574 positional arguments:
575 bar bar help
576
577 optional arguments:
578 -h, --help show this help message and exit
579 --foo [FOO] foo help
580
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000581The ``%(prog)s`` format specifier is available to fill in the program name in
582your usage messages.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000583
584
585The add_argument() method
586-------------------------
587
Georg Brandlc9007082011-01-09 09:04:08 +0000588.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
589 [const], [default], [type], [choices], [required], \
590 [help], [metavar], [dest])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000591
592 Define how a single command line argument should be parsed. Each parameter
593 has its own more detailed description below, but in short they are:
594
595 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
596 or ``-f, --foo``
597
598 * action_ - The basic type of action to be taken when this argument is
599 encountered at the command-line.
600
601 * nargs_ - The number of command-line arguments that should be consumed.
602
603 * const_ - A constant value required by some action_ and nargs_ selections.
604
605 * default_ - The value produced if the argument is absent from the
606 command-line.
607
608 * type_ - The type to which the command-line arg should be converted.
609
610 * choices_ - A container of the allowable values for the argument.
611
612 * required_ - Whether or not the command-line option may be omitted
613 (optionals only).
614
615 * help_ - A brief description of what the argument does.
616
617 * metavar_ - A name for the argument in usage messages.
618
619 * dest_ - The name of the attribute to be added to the object returned by
620 :meth:`parse_args`.
621
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000622The following sections describe how each of these are used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000623
Georg Brandle0bf91d2010-10-17 10:34:28 +0000624
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000625name or flags
626^^^^^^^^^^^^^
627
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000628The :meth:`add_argument` method must know whether an optional argument, like
629``-f`` or ``--foo``, or a positional argument, like a list of filenames, is
630expected. The first arguments passed to :meth:`add_argument` must therefore be
631either a series of flags, or a simple argument name. For example, an optional
632argument could be created like::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000633
634 >>> parser.add_argument('-f', '--foo')
635
636while a positional argument could be created like::
637
638 >>> parser.add_argument('bar')
639
640When :meth:`parse_args` is called, optional arguments will be identified by the
641``-`` prefix, and the remaining arguments will be assumed to be positional::
642
643 >>> parser = argparse.ArgumentParser(prog='PROG')
644 >>> parser.add_argument('-f', '--foo')
645 >>> parser.add_argument('bar')
646 >>> parser.parse_args(['BAR'])
647 Namespace(bar='BAR', foo=None)
648 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
649 Namespace(bar='BAR', foo='FOO')
650 >>> parser.parse_args(['--foo', 'FOO'])
651 usage: PROG [-h] [-f FOO] bar
652 PROG: error: too few arguments
653
Georg Brandle0bf91d2010-10-17 10:34:28 +0000654
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000655action
656^^^^^^
657
658:class:`ArgumentParser` objects associate command-line args with actions. These
659actions can do just about anything with the command-line args associated with
660them, though most actions simply add an attribute to the object returned by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000661:meth:`parse_args`. The ``action`` keyword argument specifies how the
662command-line args should be handled. The supported actions are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000663
664* ``'store'`` - This just stores the argument's value. This is the default
665 action. For example::
666
667 >>> parser = argparse.ArgumentParser()
668 >>> parser.add_argument('--foo')
669 >>> parser.parse_args('--foo 1'.split())
670 Namespace(foo='1')
671
672* ``'store_const'`` - This stores the value specified by the const_ keyword
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000673 argument. (Note that the const_ keyword argument defaults to the rather
674 unhelpful ``None``.) The ``'store_const'`` action is most commonly used with
675 optional arguments that specify some sort of flag. For example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000676
677 >>> parser = argparse.ArgumentParser()
678 >>> parser.add_argument('--foo', action='store_const', const=42)
679 >>> parser.parse_args('--foo'.split())
680 Namespace(foo=42)
681
682* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000683 ``False`` respectively. These are special cases of ``'store_const'``. For
684 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000685
686 >>> parser = argparse.ArgumentParser()
687 >>> parser.add_argument('--foo', action='store_true')
688 >>> parser.add_argument('--bar', action='store_false')
689 >>> parser.parse_args('--foo --bar'.split())
690 Namespace(bar=False, foo=True)
691
692* ``'append'`` - This stores a list, and appends each argument value to the
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000693 list. This is useful to allow an option to be specified multiple times.
694 Example usage::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000695
696 >>> parser = argparse.ArgumentParser()
697 >>> parser.add_argument('--foo', action='append')
698 >>> parser.parse_args('--foo 1 --foo 2'.split())
699 Namespace(foo=['1', '2'])
700
701* ``'append_const'`` - This stores a list, and appends the value specified by
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000702 the const_ keyword argument to the list. (Note that the const_ keyword
703 argument defaults to ``None``.) The ``'append_const'`` action is typically
704 useful when multiple arguments need to store constants to the same list. For
705 example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000706
707 >>> parser = argparse.ArgumentParser()
708 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
709 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
710 >>> parser.parse_args('--str --int'.split())
711 Namespace(types=[<type 'str'>, <type 'int'>])
712
713* ``'version'`` - This expects a ``version=`` keyword argument in the
714 :meth:`add_argument` call, and prints version information and exits when
715 invoked.
716
717 >>> import argparse
718 >>> parser = argparse.ArgumentParser(prog='PROG')
Steven Bethard59710962010-05-24 03:21:08 +0000719 >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
720 >>> parser.parse_args(['--version'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000721 PROG 2.0
722
723You can also specify an arbitrary action by passing an object that implements
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000724the Action API. The easiest way to do this is to extend
725:class:`argparse.Action`, supplying an appropriate ``__call__`` method. The
726``__call__`` method should accept four parameters:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000727
728* ``parser`` - The ArgumentParser object which contains this action.
729
730* ``namespace`` - The namespace object that will be returned by
731 :meth:`parse_args`. Most actions add an attribute to this object.
732
733* ``values`` - The associated command-line args, with any type-conversions
734 applied. (Type-conversions are specified with the type_ keyword argument to
735 :meth:`add_argument`.
736
737* ``option_string`` - The option string that was used to invoke this action.
738 The ``option_string`` argument is optional, and will be absent if the action
739 is associated with a positional argument.
740
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000741An example of a custom action::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000742
743 >>> class FooAction(argparse.Action):
744 ... def __call__(self, parser, namespace, values, option_string=None):
Georg Brandl571a9532010-07-26 17:00:20 +0000745 ... print('%r %r %r' % (namespace, values, option_string))
746 ... setattr(namespace, self.dest, values)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000747 ...
748 >>> parser = argparse.ArgumentParser()
749 >>> parser.add_argument('--foo', action=FooAction)
750 >>> parser.add_argument('bar', action=FooAction)
751 >>> args = parser.parse_args('1 --foo 2'.split())
752 Namespace(bar=None, foo=None) '1' None
753 Namespace(bar='1', foo=None) '2' '--foo'
754 >>> args
755 Namespace(bar='1', foo='2')
756
757
758nargs
759^^^^^
760
761ArgumentParser objects usually associate a single command-line argument with a
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000762single action to be taken. The ``nargs`` keyword argument associates a
763different number of command-line arguments with a single action.. The supported
764values are:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000765
766* N (an integer). N args from the command-line will be gathered together into a
767 list. For example::
768
Georg Brandl682d7e02010-10-06 10:26:05 +0000769 >>> parser = argparse.ArgumentParser()
770 >>> parser.add_argument('--foo', nargs=2)
771 >>> parser.add_argument('bar', nargs=1)
772 >>> parser.parse_args('c --foo a b'.split())
773 Namespace(bar=['c'], foo=['a', 'b'])
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000774
Georg Brandl682d7e02010-10-06 10:26:05 +0000775 Note that ``nargs=1`` produces a list of one item. This is different from
776 the default, in which the item is produced by itself.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000777
778* ``'?'``. One arg will be consumed from the command-line if possible, and
779 produced as a single item. If no command-line arg is present, the value from
780 default_ will be produced. Note that for optional arguments, there is an
781 additional case - the option string is present but not followed by a
782 command-line arg. In this case the value from const_ will be produced. Some
783 examples to illustrate this::
784
785 >>> parser = argparse.ArgumentParser()
786 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
787 >>> parser.add_argument('bar', nargs='?', default='d')
788 >>> parser.parse_args('XX --foo YY'.split())
789 Namespace(bar='XX', foo='YY')
790 >>> parser.parse_args('XX --foo'.split())
791 Namespace(bar='XX', foo='c')
792 >>> parser.parse_args(''.split())
793 Namespace(bar='d', foo='d')
794
795 One of the more common uses of ``nargs='?'`` is to allow optional input and
796 output files::
797
798 >>> parser = argparse.ArgumentParser()
Georg Brandle0bf91d2010-10-17 10:34:28 +0000799 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
800 ... default=sys.stdin)
801 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
802 ... default=sys.stdout)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000803 >>> parser.parse_args(['input.txt', 'output.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000804 Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
805 outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000806 >>> parser.parse_args([])
Georg Brandl04536b02011-01-09 09:31:01 +0000807 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
808 outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000809
810* ``'*'``. All command-line args present are gathered into a list. Note that
811 it generally doesn't make much sense to have more than one positional argument
812 with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
813 possible. For example::
814
815 >>> parser = argparse.ArgumentParser()
816 >>> parser.add_argument('--foo', nargs='*')
817 >>> parser.add_argument('--bar', nargs='*')
818 >>> parser.add_argument('baz', nargs='*')
819 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
820 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
821
822* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
823 list. Additionally, an error message will be generated if there wasn't at
824 least one command-line arg present. For example::
825
826 >>> parser = argparse.ArgumentParser(prog='PROG')
827 >>> parser.add_argument('foo', nargs='+')
828 >>> parser.parse_args('a b'.split())
829 Namespace(foo=['a', 'b'])
830 >>> parser.parse_args(''.split())
831 usage: PROG [-h] foo [foo ...]
832 PROG: error: too few arguments
833
834If the ``nargs`` keyword argument is not provided, the number of args consumed
835is determined by the action_. Generally this means a single command-line arg
836will be consumed and a single item (not a list) will be produced.
837
838
839const
840^^^^^
841
842The ``const`` argument of :meth:`add_argument` is used to hold constant values
843that are not read from the command line but are required for the various
844ArgumentParser actions. The two most common uses of it are:
845
846* When :meth:`add_argument` is called with ``action='store_const'`` or
847 ``action='append_const'``. These actions add the ``const`` value to one of
848 the attributes of the object returned by :meth:`parse_args`. See the action_
849 description for examples.
850
851* When :meth:`add_argument` is called with option strings (like ``-f`` or
852 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
853 followed by zero or one command-line args. When parsing the command-line, if
854 the option string is encountered with no command-line arg following it, the
855 value of ``const`` will be assumed instead. See the nargs_ description for
856 examples.
857
858The ``const`` keyword argument defaults to ``None``.
859
860
861default
862^^^^^^^
863
864All optional arguments and some positional arguments may be omitted at the
865command-line. The ``default`` keyword argument of :meth:`add_argument`, whose
866value defaults to ``None``, specifies what value should be used if the
867command-line arg is not present. For optional arguments, the ``default`` value
868is used when the option string was not present at the command line::
869
870 >>> parser = argparse.ArgumentParser()
871 >>> parser.add_argument('--foo', default=42)
872 >>> parser.parse_args('--foo 2'.split())
873 Namespace(foo='2')
874 >>> parser.parse_args(''.split())
875 Namespace(foo=42)
876
877For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
878is used when no command-line arg was present::
879
880 >>> parser = argparse.ArgumentParser()
881 >>> parser.add_argument('foo', nargs='?', default=42)
882 >>> parser.parse_args('a'.split())
883 Namespace(foo='a')
884 >>> parser.parse_args(''.split())
885 Namespace(foo=42)
886
887
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000888Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
889command-line argument was not present.::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000890
891 >>> parser = argparse.ArgumentParser()
892 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
893 >>> parser.parse_args([])
894 Namespace()
895 >>> parser.parse_args(['--foo', '1'])
896 Namespace(foo='1')
897
898
899type
900^^^^
901
902By default, ArgumentParser objects read command-line args in as simple strings.
903However, quite often the command-line string should instead be interpreted as
Georg Brandl04536b02011-01-09 09:31:01 +0000904another type, like a :class:`float` or :class:`int`. The ``type`` keyword
905argument of :meth:`add_argument` allows any necessary type-checking and
906type-conversions to be performed. Common built-in types and functions can be
907used directly as the value of the ``type`` argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000908
909 >>> parser = argparse.ArgumentParser()
910 >>> parser.add_argument('foo', type=int)
Georg Brandl04536b02011-01-09 09:31:01 +0000911 >>> parser.add_argument('bar', type=open)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000912 >>> parser.parse_args('2 temp.txt'.split())
Georg Brandl04536b02011-01-09 09:31:01 +0000913 Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000914
915To ease the use of various types of files, the argparse module provides the
916factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
Georg Brandl04536b02011-01-09 09:31:01 +0000917:func:`open` function. For example, ``FileType('w')`` can be used to create a
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000918writable file::
919
920 >>> parser = argparse.ArgumentParser()
921 >>> parser.add_argument('bar', type=argparse.FileType('w'))
922 >>> parser.parse_args(['out.txt'])
Georg Brandl04536b02011-01-09 09:31:01 +0000923 Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000924
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000925``type=`` can take any callable that takes a single string argument and returns
926the type-converted value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000927
928 >>> def perfect_square(string):
929 ... value = int(string)
930 ... sqrt = math.sqrt(value)
931 ... if sqrt != int(sqrt):
932 ... msg = "%r is not a perfect square" % string
933 ... raise argparse.ArgumentTypeError(msg)
934 ... return value
935 ...
936 >>> parser = argparse.ArgumentParser(prog='PROG')
937 >>> parser.add_argument('foo', type=perfect_square)
938 >>> parser.parse_args('9'.split())
939 Namespace(foo=9)
940 >>> parser.parse_args('7'.split())
941 usage: PROG [-h] foo
942 PROG: error: argument foo: '7' is not a perfect square
943
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000944The choices_ keyword argument may be more convenient for type checkers that
945simply check against a range of values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000946
947 >>> parser = argparse.ArgumentParser(prog='PROG')
Fred Drake44623062011-03-03 05:27:17 +0000948 >>> parser.add_argument('foo', type=int, choices=range(5, 10))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000949 >>> parser.parse_args('7'.split())
950 Namespace(foo=7)
951 >>> parser.parse_args('11'.split())
952 usage: PROG [-h] {5,6,7,8,9}
953 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
954
955See the choices_ section for more details.
956
957
958choices
959^^^^^^^
960
961Some command-line args should be selected from a restricted set of values.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000962These can be handled by passing a container object as the ``choices`` keyword
963argument to :meth:`add_argument`. When the command-line is parsed, arg values
964will be checked, and an error message will be displayed if the arg was not one
965of the acceptable values::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000966
967 >>> parser = argparse.ArgumentParser(prog='PROG')
968 >>> parser.add_argument('foo', choices='abc')
969 >>> parser.parse_args('c'.split())
970 Namespace(foo='c')
971 >>> parser.parse_args('X'.split())
972 usage: PROG [-h] {a,b,c}
973 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
974
975Note that inclusion in the ``choices`` container is checked after any type_
976conversions have been performed, so the type of the objects in the ``choices``
977container should match the type_ specified::
978
979 >>> parser = argparse.ArgumentParser(prog='PROG')
980 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
981 >>> parser.parse_args('1j'.split())
982 Namespace(foo=1j)
983 >>> parser.parse_args('-- -4'.split())
984 usage: PROG [-h] {1,1j}
985 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
986
987Any object that supports the ``in`` operator can be passed as the ``choices``
988value, so :class:`dict` objects, :class:`set` objects, custom containers,
989etc. are all supported.
990
991
992required
993^^^^^^^^
994
995In general, the argparse module assumes that flags like ``-f`` and ``--bar``
996indicate *optional* arguments, which can always be omitted at the command-line.
Benjamin Peterson98047eb2010-03-03 02:07:08 +0000997To make an option *required*, ``True`` can be specified for the ``required=``
998keyword argument to :meth:`add_argument`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000999
1000 >>> parser = argparse.ArgumentParser()
1001 >>> parser.add_argument('--foo', required=True)
1002 >>> parser.parse_args(['--foo', 'BAR'])
1003 Namespace(foo='BAR')
1004 >>> parser.parse_args([])
1005 usage: argparse.py [-h] [--foo FOO]
1006 argparse.py: error: option --foo is required
1007
1008As the example shows, if an option is marked as ``required``, :meth:`parse_args`
1009will report an error if that option is not present at the command line.
1010
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001011.. note::
1012
1013 Required options are generally considered bad form because users expect
1014 *options* to be *optional*, and thus they should be avoided when possible.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001015
1016
1017help
1018^^^^
1019
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001020The ``help`` value is a string containing a brief description of the argument.
1021When a user requests help (usually by using ``-h`` or ``--help`` at the
1022command-line), these ``help`` descriptions will be displayed with each
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001023argument::
1024
1025 >>> parser = argparse.ArgumentParser(prog='frobble')
1026 >>> parser.add_argument('--foo', action='store_true',
1027 ... help='foo the bars before frobbling')
1028 >>> parser.add_argument('bar', nargs='+',
1029 ... help='one of the bars to be frobbled')
1030 >>> parser.parse_args('-h'.split())
1031 usage: frobble [-h] [--foo] bar [bar ...]
1032
1033 positional arguments:
1034 bar one of the bars to be frobbled
1035
1036 optional arguments:
1037 -h, --help show this help message and exit
1038 --foo foo the bars before frobbling
1039
1040The ``help`` strings can include various format specifiers to avoid repetition
1041of things like the program name or the argument default_. The available
1042specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1043:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1044
1045 >>> parser = argparse.ArgumentParser(prog='frobble')
1046 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1047 ... help='the bar to %(prog)s (default: %(default)s)')
1048 >>> parser.print_help()
1049 usage: frobble [-h] [bar]
1050
1051 positional arguments:
1052 bar the bar to frobble (default: 42)
1053
1054 optional arguments:
1055 -h, --help show this help message and exit
1056
1057
1058metavar
1059^^^^^^^
1060
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001061When :class:`ArgumentParser` generates help messages, it need some way to refer
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001062to each expected argument. By default, ArgumentParser objects use the dest_
1063value as the "name" of each object. By default, for positional argument
1064actions, the dest_ value is used directly, and for optional argument actions,
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001065the dest_ value is uppercased. So, a single positional argument with
1066``dest='bar'`` will that argument will be referred to as ``bar``. A single
1067optional argument ``--foo`` that should be followed by a single command-line arg
1068will be referred to as ``FOO``. An example::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001069
1070 >>> parser = argparse.ArgumentParser()
1071 >>> parser.add_argument('--foo')
1072 >>> parser.add_argument('bar')
1073 >>> parser.parse_args('X --foo Y'.split())
1074 Namespace(bar='X', foo='Y')
1075 >>> parser.print_help()
1076 usage: [-h] [--foo FOO] bar
1077
1078 positional arguments:
1079 bar
1080
1081 optional arguments:
1082 -h, --help show this help message and exit
1083 --foo FOO
1084
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001085An alternative name can be specified with ``metavar``::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001086
1087 >>> parser = argparse.ArgumentParser()
1088 >>> parser.add_argument('--foo', metavar='YYY')
1089 >>> parser.add_argument('bar', metavar='XXX')
1090 >>> parser.parse_args('X --foo Y'.split())
1091 Namespace(bar='X', foo='Y')
1092 >>> parser.print_help()
1093 usage: [-h] [--foo YYY] XXX
1094
1095 positional arguments:
1096 XXX
1097
1098 optional arguments:
1099 -h, --help show this help message and exit
1100 --foo YYY
1101
1102Note that ``metavar`` only changes the *displayed* name - the name of the
1103attribute on the :meth:`parse_args` object is still determined by the dest_
1104value.
1105
1106Different values of ``nargs`` may cause the metavar to be used multiple times.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001107Providing a tuple to ``metavar`` specifies a different display for each of the
1108arguments::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001109
1110 >>> parser = argparse.ArgumentParser(prog='PROG')
1111 >>> parser.add_argument('-x', nargs=2)
1112 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1113 >>> parser.print_help()
1114 usage: PROG [-h] [-x X X] [--foo bar baz]
1115
1116 optional arguments:
1117 -h, --help show this help message and exit
1118 -x X X
1119 --foo bar baz
1120
1121
1122dest
1123^^^^
1124
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001125Most :class:`ArgumentParser` actions add some value as an attribute of the
1126object returned by :meth:`parse_args`. The name of this attribute is determined
1127by the ``dest`` keyword argument of :meth:`add_argument`. For positional
1128argument actions, ``dest`` is normally supplied as the first argument to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001129:meth:`add_argument`::
1130
1131 >>> parser = argparse.ArgumentParser()
1132 >>> parser.add_argument('bar')
1133 >>> parser.parse_args('XXX'.split())
1134 Namespace(bar='XXX')
1135
1136For optional argument actions, the value of ``dest`` is normally inferred from
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001137the option strings. :class:`ArgumentParser` generates the value of ``dest`` by
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001138taking the first long option string and stripping away the initial ``'--'``
1139string. If no long option strings were supplied, ``dest`` will be derived from
1140the first short option string by stripping the initial ``'-'`` character. Any
1141internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
1142the string is a valid attribute name. The examples below illustrate this
1143behavior::
1144
1145 >>> parser = argparse.ArgumentParser()
1146 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1147 >>> parser.add_argument('-x', '-y')
1148 >>> parser.parse_args('-f 1 -x 2'.split())
1149 Namespace(foo_bar='1', x='2')
1150 >>> parser.parse_args('--foo 1 -y 2'.split())
1151 Namespace(foo_bar='1', x='2')
1152
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001153``dest`` allows a custom attribute name to be provided::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001154
1155 >>> parser = argparse.ArgumentParser()
1156 >>> parser.add_argument('--foo', dest='bar')
1157 >>> parser.parse_args('--foo XXX'.split())
1158 Namespace(bar='XXX')
1159
1160
1161The parse_args() method
1162-----------------------
1163
Georg Brandle0bf91d2010-10-17 10:34:28 +00001164.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001165
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001166 Convert argument strings to objects and assign them as attributes of the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001167 namespace. Return the populated namespace.
1168
1169 Previous calls to :meth:`add_argument` determine exactly what objects are
1170 created and how they are assigned. See the documentation for
1171 :meth:`add_argument` for details.
1172
1173 By default, the arg strings are taken from :data:`sys.argv`, and a new empty
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001174 :class:`Namespace` object is created for the attributes.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001175
Georg Brandle0bf91d2010-10-17 10:34:28 +00001176
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001177Option value syntax
1178^^^^^^^^^^^^^^^^^^^
1179
1180The :meth:`parse_args` method supports several ways of specifying the value of
1181an option (if it takes one). In the simplest case, the option and its value are
1182passed as two separate arguments::
1183
1184 >>> parser = argparse.ArgumentParser(prog='PROG')
1185 >>> parser.add_argument('-x')
1186 >>> parser.add_argument('--foo')
1187 >>> parser.parse_args('-x X'.split())
1188 Namespace(foo=None, x='X')
1189 >>> parser.parse_args('--foo FOO'.split())
1190 Namespace(foo='FOO', x=None)
1191
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001192For long options (options with names longer than a single character), the option
1193and value can also be passed as a single command line argument, using ``=`` to
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001194separate them::
1195
1196 >>> parser.parse_args('--foo=FOO'.split())
1197 Namespace(foo='FOO', x=None)
1198
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001199For short options (options only one character long), the option and its value
1200can be concatenated::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001201
1202 >>> parser.parse_args('-xX'.split())
1203 Namespace(foo=None, x='X')
1204
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001205Several short options can be joined together, using only a single ``-`` prefix,
1206as long as only the last option (or none of them) requires a value::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001207
1208 >>> parser = argparse.ArgumentParser(prog='PROG')
1209 >>> parser.add_argument('-x', action='store_true')
1210 >>> parser.add_argument('-y', action='store_true')
1211 >>> parser.add_argument('-z')
1212 >>> parser.parse_args('-xyzZ'.split())
1213 Namespace(x=True, y=True, z='Z')
1214
1215
1216Invalid arguments
1217^^^^^^^^^^^^^^^^^
1218
1219While parsing the command-line, ``parse_args`` checks for a variety of errors,
1220including ambiguous options, invalid types, invalid options, wrong number of
1221positional arguments, etc. When it encounters such an error, it exits and
1222prints the error along with a usage message::
1223
1224 >>> parser = argparse.ArgumentParser(prog='PROG')
1225 >>> parser.add_argument('--foo', type=int)
1226 >>> parser.add_argument('bar', nargs='?')
1227
1228 >>> # invalid type
1229 >>> parser.parse_args(['--foo', 'spam'])
1230 usage: PROG [-h] [--foo FOO] [bar]
1231 PROG: error: argument --foo: invalid int value: 'spam'
1232
1233 >>> # invalid option
1234 >>> parser.parse_args(['--bar'])
1235 usage: PROG [-h] [--foo FOO] [bar]
1236 PROG: error: no such option: --bar
1237
1238 >>> # wrong number of arguments
1239 >>> parser.parse_args(['spam', 'badger'])
1240 usage: PROG [-h] [--foo FOO] [bar]
1241 PROG: error: extra arguments found: badger
1242
1243
1244Arguments containing ``"-"``
1245^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1246
1247The ``parse_args`` method attempts to give errors whenever the user has clearly
1248made a mistake, but some situations are inherently ambiguous. For example, the
1249command-line arg ``'-1'`` could either be an attempt to specify an option or an
1250attempt to provide a positional argument. The ``parse_args`` method is cautious
1251here: positional arguments may only begin with ``'-'`` if they look like
1252negative numbers and there are no options in the parser that look like negative
1253numbers::
1254
1255 >>> parser = argparse.ArgumentParser(prog='PROG')
1256 >>> parser.add_argument('-x')
1257 >>> parser.add_argument('foo', nargs='?')
1258
1259 >>> # no negative number options, so -1 is a positional argument
1260 >>> parser.parse_args(['-x', '-1'])
1261 Namespace(foo=None, x='-1')
1262
1263 >>> # no negative number options, so -1 and -5 are positional arguments
1264 >>> parser.parse_args(['-x', '-1', '-5'])
1265 Namespace(foo='-5', x='-1')
1266
1267 >>> parser = argparse.ArgumentParser(prog='PROG')
1268 >>> parser.add_argument('-1', dest='one')
1269 >>> parser.add_argument('foo', nargs='?')
1270
1271 >>> # negative number options present, so -1 is an option
1272 >>> parser.parse_args(['-1', 'X'])
1273 Namespace(foo=None, one='X')
1274
1275 >>> # negative number options present, so -2 is an option
1276 >>> parser.parse_args(['-2'])
1277 usage: PROG [-h] [-1 ONE] [foo]
1278 PROG: error: no such option: -2
1279
1280 >>> # negative number options present, so both -1s are options
1281 >>> parser.parse_args(['-1', '-1'])
1282 usage: PROG [-h] [-1 ONE] [foo]
1283 PROG: error: argument -1: expected one argument
1284
1285If you have positional arguments that must begin with ``'-'`` and don't look
1286like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1287``parse_args`` that everything after that is a positional argument::
1288
1289 >>> parser.parse_args(['--', '-f'])
1290 Namespace(foo='-f', one=None)
1291
1292
1293Argument abbreviations
1294^^^^^^^^^^^^^^^^^^^^^^
1295
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001296The :meth:`parse_args` method allows long options to be abbreviated if the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001297abbreviation is unambiguous::
1298
1299 >>> parser = argparse.ArgumentParser(prog='PROG')
1300 >>> parser.add_argument('-bacon')
1301 >>> parser.add_argument('-badger')
1302 >>> parser.parse_args('-bac MMM'.split())
1303 Namespace(bacon='MMM', badger=None)
1304 >>> parser.parse_args('-bad WOOD'.split())
1305 Namespace(bacon=None, badger='WOOD')
1306 >>> parser.parse_args('-ba BA'.split())
1307 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1308 PROG: error: ambiguous option: -ba could match -badger, -bacon
1309
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001310An error is produced for arguments that could produce more than one options.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001311
1312
1313Beyond ``sys.argv``
1314^^^^^^^^^^^^^^^^^^^
1315
1316Sometimes it may be useful to have an ArgumentParser parse args other than those
1317of :data:`sys.argv`. This can be accomplished by passing a list of strings to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001318``parse_args``. This is useful for testing at the interactive prompt::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001319
1320 >>> parser = argparse.ArgumentParser()
1321 >>> parser.add_argument(
Fred Drake44623062011-03-03 05:27:17 +00001322 ... 'integers', metavar='int', type=int, choices=range(10),
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001323 ... nargs='+', help='an integer in the range 0..9')
1324 >>> parser.add_argument(
1325 ... '--sum', dest='accumulate', action='store_const', const=sum,
1326 ... default=max, help='sum the integers (default: find the max)')
1327 >>> parser.parse_args(['1', '2', '3', '4'])
1328 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1329 >>> parser.parse_args('1 2 3 4 --sum'.split())
1330 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1331
1332
1333Custom namespaces
1334^^^^^^^^^^^^^^^^^
1335
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001336It may also be useful to have an :class:`ArgumentParser` assign attributes to an
1337already existing object, rather than the newly-created :class:`Namespace` object
1338that is normally used. This can be achieved by specifying the ``namespace=``
1339keyword argument::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001340
Éric Araujo28053fb2010-11-22 03:09:19 +00001341 >>> class C:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001342 ... pass
1343 ...
1344 >>> c = C()
1345 >>> parser = argparse.ArgumentParser()
1346 >>> parser.add_argument('--foo')
1347 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1348 >>> c.foo
1349 'BAR'
1350
1351
1352Other utilities
1353---------------
1354
1355Sub-commands
1356^^^^^^^^^^^^
1357
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001358.. method:: ArgumentParser.add_subparsers()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001359
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001360 Many programs split up their functionality into a number of sub-commands,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001361 for example, the ``svn`` program can invoke sub-commands like ``svn
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001362 checkout``, ``svn update``, and ``svn commit``. Splitting up functionality
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001363 this way can be a particularly good idea when a program performs several
1364 different functions which require different kinds of command-line arguments.
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001365 :class:`ArgumentParser` supports the creation of such sub-commands with the
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001366 :meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
1367 called with no arguments and returns an special action object. This object
1368 has a single method, ``add_parser``, which takes a command name and any
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001369 :class:`ArgumentParser` constructor arguments, and returns an
1370 :class:`ArgumentParser` object that can be modified as usual.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001371
1372 Some example usage::
1373
1374 >>> # create the top-level parser
1375 >>> parser = argparse.ArgumentParser(prog='PROG')
1376 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1377 >>> subparsers = parser.add_subparsers(help='sub-command help')
1378 >>>
1379 >>> # create the parser for the "a" command
1380 >>> parser_a = subparsers.add_parser('a', help='a help')
1381 >>> parser_a.add_argument('bar', type=int, help='bar help')
1382 >>>
1383 >>> # create the parser for the "b" command
1384 >>> parser_b = subparsers.add_parser('b', help='b help')
1385 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1386 >>>
1387 >>> # parse some arg lists
1388 >>> parser.parse_args(['a', '12'])
1389 Namespace(bar=12, foo=False)
1390 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1391 Namespace(baz='Z', foo=True)
1392
1393 Note that the object returned by :meth:`parse_args` will only contain
1394 attributes for the main parser and the subparser that was selected by the
1395 command line (and not any other subparsers). So in the example above, when
1396 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
1397 present, and when the ``"b"`` command is specified, only the ``foo`` and
1398 ``baz`` attributes are present.
1399
1400 Similarly, when a help message is requested from a subparser, only the help
1401 for that particular parser will be printed. The help message will not
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001402 include parent parser or sibling parser messages. (A help message for each
1403 subparser command, however, can be given by supplying the ``help=`` argument
1404 to ``add_parser`` as above.)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001405
1406 ::
1407
1408 >>> parser.parse_args(['--help'])
1409 usage: PROG [-h] [--foo] {a,b} ...
1410
1411 positional arguments:
1412 {a,b} sub-command help
1413 a a help
1414 b b help
1415
1416 optional arguments:
1417 -h, --help show this help message and exit
1418 --foo foo help
1419
1420 >>> parser.parse_args(['a', '--help'])
1421 usage: PROG a [-h] bar
1422
1423 positional arguments:
1424 bar bar help
1425
1426 optional arguments:
1427 -h, --help show this help message and exit
1428
1429 >>> parser.parse_args(['b', '--help'])
1430 usage: PROG b [-h] [--baz {X,Y,Z}]
1431
1432 optional arguments:
1433 -h, --help show this help message and exit
1434 --baz {X,Y,Z} baz help
1435
1436 The :meth:`add_subparsers` method also supports ``title`` and ``description``
1437 keyword arguments. When either is present, the subparser's commands will
1438 appear in their own group in the help output. For example::
1439
1440 >>> parser = argparse.ArgumentParser()
1441 >>> subparsers = parser.add_subparsers(title='subcommands',
1442 ... description='valid subcommands',
1443 ... help='additional help')
1444 >>> subparsers.add_parser('foo')
1445 >>> subparsers.add_parser('bar')
1446 >>> parser.parse_args(['-h'])
1447 usage: [-h] {foo,bar} ...
1448
1449 optional arguments:
1450 -h, --help show this help message and exit
1451
1452 subcommands:
1453 valid subcommands
1454
1455 {foo,bar} additional help
1456
Steven Bethardfd311a72010-12-18 11:19:23 +00001457 Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
1458 which allows multiple strings to refer to the same subparser. This example,
1459 like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
1460
1461 >>> parser = argparse.ArgumentParser()
1462 >>> subparsers = parser.add_subparsers()
1463 >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
1464 >>> checkout.add_argument('foo')
1465 >>> parser.parse_args(['co', 'bar'])
1466 Namespace(foo='bar')
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001467
1468 One particularly effective way of handling sub-commands is to combine the use
1469 of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
1470 that each subparser knows which Python function it should execute. For
1471 example::
1472
1473 >>> # sub-command functions
1474 >>> def foo(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001475 ... print(args.x * args.y)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001476 ...
1477 >>> def bar(args):
Benjamin Petersonb2deb112010-03-03 02:09:18 +00001478 ... print('((%s))' % args.z)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001479 ...
1480 >>> # create the top-level parser
1481 >>> parser = argparse.ArgumentParser()
1482 >>> subparsers = parser.add_subparsers()
1483 >>>
1484 >>> # create the parser for the "foo" command
1485 >>> parser_foo = subparsers.add_parser('foo')
1486 >>> parser_foo.add_argument('-x', type=int, default=1)
1487 >>> parser_foo.add_argument('y', type=float)
1488 >>> parser_foo.set_defaults(func=foo)
1489 >>>
1490 >>> # create the parser for the "bar" command
1491 >>> parser_bar = subparsers.add_parser('bar')
1492 >>> parser_bar.add_argument('z')
1493 >>> parser_bar.set_defaults(func=bar)
1494 >>>
1495 >>> # parse the args and call whatever function was selected
1496 >>> args = parser.parse_args('foo 1 -x 2'.split())
1497 >>> args.func(args)
1498 2.0
1499 >>>
1500 >>> # parse the args and call whatever function was selected
1501 >>> args = parser.parse_args('bar XYZYX'.split())
1502 >>> args.func(args)
1503 ((XYZYX))
1504
Steven Bethardfd311a72010-12-18 11:19:23 +00001505 This way, you can let :meth:`parse_args` do the job of calling the
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001506 appropriate function after argument parsing is complete. Associating
1507 functions with actions like this is typically the easiest way to handle the
1508 different actions for each of your subparsers. However, if it is necessary
1509 to check the name of the subparser that was invoked, the ``dest`` keyword
1510 argument to the :meth:`add_subparsers` call will work::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001511
1512 >>> parser = argparse.ArgumentParser()
1513 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1514 >>> subparser1 = subparsers.add_parser('1')
1515 >>> subparser1.add_argument('-x')
1516 >>> subparser2 = subparsers.add_parser('2')
1517 >>> subparser2.add_argument('y')
1518 >>> parser.parse_args(['2', 'frobble'])
1519 Namespace(subparser_name='2', y='frobble')
1520
1521
1522FileType objects
1523^^^^^^^^^^^^^^^^
1524
1525.. class:: FileType(mode='r', bufsize=None)
1526
1527 The :class:`FileType` factory creates objects that can be passed to the type
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001528 argument of :meth:`ArgumentParser.add_argument`. Arguments that have
1529 :class:`FileType` objects as their type will open command-line args as files
1530 with the requested modes and buffer sizes:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001531
1532 >>> parser = argparse.ArgumentParser()
1533 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1534 >>> parser.parse_args(['--output', 'out'])
Georg Brandl04536b02011-01-09 09:31:01 +00001535 Namespace(output=<_io.BufferedWriter name='out'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001536
1537 FileType objects understand the pseudo-argument ``'-'`` and automatically
1538 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1539 ``sys.stdout`` for writable :class:`FileType` objects:
1540
1541 >>> parser = argparse.ArgumentParser()
1542 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1543 >>> parser.parse_args(['-'])
Georg Brandl04536b02011-01-09 09:31:01 +00001544 Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001545
1546
1547Argument groups
1548^^^^^^^^^^^^^^^
1549
Georg Brandle0bf91d2010-10-17 10:34:28 +00001550.. method:: ArgumentParser.add_argument_group(title=None, description=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001551
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001552 By default, :class:`ArgumentParser` groups command-line arguments into
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001553 "positional arguments" and "optional arguments" when displaying help
1554 messages. When there is a better conceptual grouping of arguments than this
1555 default one, appropriate groups can be created using the
1556 :meth:`add_argument_group` method::
1557
1558 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1559 >>> group = parser.add_argument_group('group')
1560 >>> group.add_argument('--foo', help='foo help')
1561 >>> group.add_argument('bar', help='bar help')
1562 >>> parser.print_help()
1563 usage: PROG [--foo FOO] bar
1564
1565 group:
1566 bar bar help
1567 --foo FOO foo help
1568
1569 The :meth:`add_argument_group` method returns an argument group object which
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001570 has an :meth:`~ArgumentParser.add_argument` method just like a regular
1571 :class:`ArgumentParser`. When an argument is added to the group, the parser
1572 treats it just like a normal argument, but displays the argument in a
1573 separate group for help messages. The :meth:`add_argument_group` method
Georg Brandle0bf91d2010-10-17 10:34:28 +00001574 accepts *title* and *description* arguments which can be used to
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001575 customize this display::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001576
1577 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1578 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1579 >>> group1.add_argument('foo', help='foo help')
1580 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1581 >>> group2.add_argument('--bar', help='bar help')
1582 >>> parser.print_help()
1583 usage: PROG [--bar BAR] foo
1584
1585 group1:
1586 group1 description
1587
1588 foo foo help
1589
1590 group2:
1591 group2 description
1592
1593 --bar BAR bar help
1594
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001595 Note that any arguments not your user defined groups will end up back in the
1596 usual "positional arguments" and "optional arguments" sections.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001597
1598
1599Mutual exclusion
1600^^^^^^^^^^^^^^^^
1601
Georg Brandle0bf91d2010-10-17 10:34:28 +00001602.. method:: add_mutually_exclusive_group(required=False)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001603
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001604 Create a mutually exclusive group. argparse will make sure that only one of
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001605 the arguments in the mutually exclusive group was present on the command
1606 line::
1607
1608 >>> parser = argparse.ArgumentParser(prog='PROG')
1609 >>> group = parser.add_mutually_exclusive_group()
1610 >>> group.add_argument('--foo', action='store_true')
1611 >>> group.add_argument('--bar', action='store_false')
1612 >>> parser.parse_args(['--foo'])
1613 Namespace(bar=True, foo=True)
1614 >>> parser.parse_args(['--bar'])
1615 Namespace(bar=False, foo=False)
1616 >>> parser.parse_args(['--foo', '--bar'])
1617 usage: PROG [-h] [--foo | --bar]
1618 PROG: error: argument --bar: not allowed with argument --foo
1619
Georg Brandle0bf91d2010-10-17 10:34:28 +00001620 The :meth:`add_mutually_exclusive_group` method also accepts a *required*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001621 argument, to indicate that at least one of the mutually exclusive arguments
1622 is required::
1623
1624 >>> parser = argparse.ArgumentParser(prog='PROG')
1625 >>> group = parser.add_mutually_exclusive_group(required=True)
1626 >>> group.add_argument('--foo', action='store_true')
1627 >>> group.add_argument('--bar', action='store_false')
1628 >>> parser.parse_args([])
1629 usage: PROG [-h] (--foo | --bar)
1630 PROG: error: one of the arguments --foo --bar is required
1631
1632 Note that currently mutually exclusive argument groups do not support the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001633 *title* and *description* arguments of :meth:`add_argument_group`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001634
1635
1636Parser defaults
1637^^^^^^^^^^^^^^^
1638
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001639.. method:: ArgumentParser.set_defaults(**kwargs)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001640
1641 Most of the time, the attributes of the object returned by :meth:`parse_args`
1642 will be fully determined by inspecting the command-line args and the argument
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001643 actions. :meth:`ArgumentParser.set_defaults` allows some additional
1644 attributes that are determined without any inspection of the command-line to
1645 be added::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001646
1647 >>> parser = argparse.ArgumentParser()
1648 >>> parser.add_argument('foo', type=int)
1649 >>> parser.set_defaults(bar=42, baz='badger')
1650 >>> parser.parse_args(['736'])
1651 Namespace(bar=42, baz='badger', foo=736)
1652
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001653 Note that parser-level defaults always override argument-level defaults::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001654
1655 >>> parser = argparse.ArgumentParser()
1656 >>> parser.add_argument('--foo', default='bar')
1657 >>> parser.set_defaults(foo='spam')
1658 >>> parser.parse_args([])
1659 Namespace(foo='spam')
1660
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001661 Parser-level defaults can be particularly useful when working with multiple
1662 parsers. See the :meth:`~ArgumentParser.add_subparsers` method for an
1663 example of this type.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001664
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001665.. method:: ArgumentParser.get_default(dest)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001666
1667 Get the default value for a namespace attribute, as set by either
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001668 :meth:`~ArgumentParser.add_argument` or by
1669 :meth:`~ArgumentParser.set_defaults`::
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001670
1671 >>> parser = argparse.ArgumentParser()
1672 >>> parser.add_argument('--foo', default='badger')
1673 >>> parser.get_default('foo')
1674 'badger'
1675
1676
1677Printing help
1678^^^^^^^^^^^^^
1679
1680In most typical applications, :meth:`parse_args` will take care of formatting
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001681and printing any usage or error messages. However, several formatting methods
1682are available:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001683
Georg Brandle0bf91d2010-10-17 10:34:28 +00001684.. method:: ArgumentParser.print_usage(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001685
1686 Print a brief description of how the :class:`ArgumentParser` should be
R. David Murray32e17712010-12-18 16:39:06 +00001687 invoked on the command line. If *file* is ``None``, :data:`sys.stdout` is
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001688 assumed.
1689
Georg Brandle0bf91d2010-10-17 10:34:28 +00001690.. method:: ArgumentParser.print_help(file=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001691
1692 Print a help message, including the program usage and information about the
Georg Brandle0bf91d2010-10-17 10:34:28 +00001693 arguments registered with the :class:`ArgumentParser`. If *file* is
R. David Murray32e17712010-12-18 16:39:06 +00001694 ``None``, :data:`sys.stdout` is assumed.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001695
1696There are also variants of these methods that simply return a string instead of
1697printing it:
1698
Georg Brandle0bf91d2010-10-17 10:34:28 +00001699.. method:: ArgumentParser.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001700
1701 Return a string containing a brief description of how the
1702 :class:`ArgumentParser` should be invoked on the command line.
1703
Georg Brandle0bf91d2010-10-17 10:34:28 +00001704.. method:: ArgumentParser.format_help()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001705
1706 Return a string containing a help message, including the program usage and
1707 information about the arguments registered with the :class:`ArgumentParser`.
1708
1709
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001710Partial parsing
1711^^^^^^^^^^^^^^^
1712
Georg Brandle0bf91d2010-10-17 10:34:28 +00001713.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001714
1715Sometimes a script may only parse a few of the command line arguments, passing
1716the remaining arguments on to another script or program. In these cases, the
1717:meth:`parse_known_args` method can be useful. It works much like
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001718:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
1719extra arguments are present. Instead, it returns a two item tuple containing
1720the populated namespace and the list of remaining argument strings.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001721
1722::
1723
1724 >>> parser = argparse.ArgumentParser()
1725 >>> parser.add_argument('--foo', action='store_true')
1726 >>> parser.add_argument('bar')
1727 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1728 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1729
1730
1731Customizing file parsing
1732^^^^^^^^^^^^^^^^^^^^^^^^
1733
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001734.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001735
Georg Brandle0bf91d2010-10-17 10:34:28 +00001736 Arguments that are read from a file (see the *fromfile_prefix_chars*
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001737 keyword argument to the :class:`ArgumentParser` constructor) are read one
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001738 argument per line. :meth:`convert_arg_line_to_args` can be overriden for
1739 fancier reading.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001740
Georg Brandle0bf91d2010-10-17 10:34:28 +00001741 This method takes a single argument *arg_line* which is a string read from
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001742 the argument file. It returns a list of arguments parsed from this string.
1743 The method is called once per line read from the argument file, in order.
1744
1745 A useful override of this method is one that treats each space-separated word
1746 as an argument::
1747
1748 def convert_arg_line_to_args(self, arg_line):
1749 for arg in arg_line.split():
1750 if not arg.strip():
1751 continue
1752 yield arg
1753
1754
Georg Brandl93754922010-10-17 10:28:04 +00001755Exiting methods
1756^^^^^^^^^^^^^^^
1757
1758.. method:: ArgumentParser.exit(status=0, message=None)
1759
1760 This method terminates the program, exiting with the specified *status*
1761 and, if given, it prints a *message* before that.
1762
1763.. method:: ArgumentParser.error(message)
1764
1765 This method prints a usage message including the *message* to the
1766 standard output and terminates the program with a status code of 2.
1767
Raymond Hettinger677e10a2010-12-07 06:45:30 +00001768.. _upgrading-optparse-code:
Georg Brandl93754922010-10-17 10:28:04 +00001769
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001770Upgrading optparse code
1771-----------------------
1772
1773Originally, the argparse module had attempted to maintain compatibility with
1774optparse. However, optparse was difficult to extend transparently, particularly
1775with the changes required to support the new ``nargs=`` specifiers and better
Georg Brandl386bc6d2010-04-25 10:19:53 +00001776usage messages. When most everything in optparse had either been copy-pasted
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001777over or monkey-patched, it no longer seemed practical to try to maintain the
1778backwards compatibility.
1779
1780A partial upgrade path from optparse to argparse:
1781
Georg Brandlc9007082011-01-09 09:04:08 +00001782* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
1783 calls.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001784
1785* Replace ``options, args = parser.parse_args()`` with ``args =
Georg Brandlc9007082011-01-09 09:04:08 +00001786 parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
1787 calls for the positional arguments.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001788
1789* Replace callback actions and the ``callback_*`` keyword arguments with
1790 ``type`` or ``action`` arguments.
1791
1792* Replace string names for ``type`` keyword arguments with the corresponding
1793 type objects (e.g. int, float, complex, etc).
1794
Benjamin Peterson98047eb2010-03-03 02:07:08 +00001795* Replace :class:`optparse.Values` with :class:`Namespace` and
1796 :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
1797 :exc:`ArgumentError`.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001798
1799* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
1800 the standard python syntax to use dictionaries to format strings, that is,
1801 ``%(default)s`` and ``%(prog)s``.
Steven Bethard59710962010-05-24 03:21:08 +00001802
1803* Replace the OptionParser constructor ``version`` argument with a call to
1804 ``parser.add_argument('--version', action='version', version='<the version>')``