blob: 750e8198167b983b00ede6f72e9e230f02fb6264 [file] [log] [blame]
Benjamin Petersona39e9662010-03-02 22:05:59 +00001:mod:`argparse` -- Parser for command line options, arguments and sub-commands
2==============================================================================
3
4.. module:: argparse
5 :synopsis: Command-line option and argument parsing library.
6.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
7.. versionadded:: 2.7
8.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>
9
10
11The :mod:`argparse` module makes it easy to write user friendly command line
12interfaces. You define what arguments your program requires, and
13:mod:`argparse` will figure out how to parse those out of ``sys.argv``. The
14:mod:`argparse` module also automatically generates help and usage messages
15based on the arguments you have defined, and issues errors when users give your
16program invalid arguments.
17
18Example
19-------
20
21As an example, the following code is a Python program that takes a list of
22integers and produces either the sum or the max::
23
24 import argparse
25
26 parser = argparse.ArgumentParser(description='Process some integers.')
27 parser.add_argument('integers', metavar='N', type=int, nargs='+',
28 help='an integer for the accumulator')
29 parser.add_argument('--sum', dest='accumulate', action='store_const',
30 const=sum, default=max,
31 help='sum the integers (default: find the max)')
32
33 args = parser.parse_args()
34 print args.accumulate(args.integers)
35
36Assuming the Python code above is saved into a file called ``prog.py``, it can
37be run at the command line and provides useful help messages::
38
39 $ prog.py -h
40 usage: prog.py [-h] [--sum] N [N ...]
41
42 Process some integers.
43
44 positional arguments:
45 N an integer for the accumulator
46
47 optional arguments:
48 -h, --help show this help message and exit
49 --sum sum the integers (default: find the max)
50
51When run with the appropriate arguments, it prints either the sum or the max of
52the command-line integers::
53
54 $ prog.py 1 2 3 4
55 4
56
57 $ prog.py 1 2 3 4 --sum
58 10
59
60If invalid arguments are passed in, it will issue an error::
61
62 $ prog.py a b c
63 usage: prog.py [-h] [--sum] N [N ...]
64 prog.py: error: argument N: invalid int value: 'a'
65
66The following sections walk you through this example.
67
68Creating a parser
69^^^^^^^^^^^^^^^^^
70
71Pretty much every script that uses the :mod:`argparse` module will start out by
72creating an :class:`ArgumentParser` object::
73
74 >>> parser = argparse.ArgumentParser(description='Process some integers.')
75
76The :class:`ArgumentParser` object will hold all the information necessary to
77parse the command line into a more manageable form for your program.
78
79
80Adding arguments
81^^^^^^^^^^^^^^^^
82
83Once you've created an :class:`ArgumentParser`, you'll want to fill it with
84information about your program arguments. You typically do this by making calls
85to the :meth:`add_argument` method. Generally, these calls tell the
86:class:`ArgumentParser` how to take the strings on the command line and turn
87them into objects for you. This information is stored and used when
88:meth:`parse_args` is called. For example, if we add some arguments like this::
89
90 >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
91 ... help='an integer for the accumulator')
92 >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
93 ... const=sum, default=max,
94 ... help='sum the integers (default: find the max)')
95
96when we later call :meth:`parse_args`, we can expect it to return an object
97with two attributes, ``integers`` and ``accumulate``. The ``integers``
98attribute will be a list of one or more ints, and the ``accumulate`` attribute
99will be either the ``sum`` function, if ``--sum`` was specified at the command
100line, or the ``max`` function if it was not.
101
102Parsing arguments
103^^^^^^^^^^^^^^^^^
104
105Once an :class:`ArgumentParser` has been initialized with appropriate calls to
106:meth:`add_argument`, it can be instructed to parse the command-line args by
107calling the :meth:`parse_args` method. This will inspect the command-line,
108convert each arg to the appropriate type and then invoke the appropriate
109action. In most cases, this means a simple namespace object will be built up
110from attributes parsed out of the command-line::
111
112 >>> parser.parse_args(['--sum', '7', '-1', '42'])
113 Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
114
115In a script, :meth:`parse_args` will typically be called with no arguments, and
116the :class:`ArgumentParser` will automatically determine the command-line args
117from ``sys.argv``. That's pretty much it. You're now ready to go write some
118command line interfaces!
119
120
121ArgumentParser objects
122----------------------
123
124.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class])
125
126 Create a new :class:`ArgumentParser` object. Each parameter has its own more
127 detailed description below, but in short they are:
128
129 * description_ - Text to display before the argument help.
130
131 * epilog_ - Text to display after the argument help.
132
133 * add_help_ - Add a -h/--help option to the parser. (default: True)
134
135 * argument_default_ - Set the global default value for arguments.
136 (default: None)
137
138 * parents_ - A list of :class:ArgumentParser objects whose arguments should
139 also be included.
140
141 * prefix_chars_ - The set of characters that prefix optional arguments.
142 (default: '-')
143
144 * fromfile_prefix_chars_ - The set of characters that prefix files from
145 which additional arguments should be read. (default: None)
146
147 * formatter_class_ - A class for customizing the help output.
148
149 * conflict_handler_ - Usually unnecessary, defines strategy for resolving
150 conflicting optionals.
151
152 * prog_ - Usually unnecessary, the name of the program
153 (default: ``sys.argv[0]``)
154
155 * usage_ - Usually unnecessary, the string describing the program usage
156 (default: generated)
157
158 The following sections describe how each of these are used.
159
160
161description
162^^^^^^^^^^^
163
164Most calls to the ArgumentParser constructor will use the ``description=``
165keyword argument. This argument gives a brief description of what the program
166does and how it works. In help messages, the description is displayed between
167the command-line usage string and the help messages for the various arguments::
168
169 >>> parser = argparse.ArgumentParser(description='A foo that bars')
170 >>> parser.print_help()
171 usage: argparse.py [-h]
172
173 A foo that bars
174
175 optional arguments:
176 -h, --help show this help message and exit
177
178By default, the description will be line-wrapped so that it fits within the
179given space. To change this behavior, see the formatter_class_ argument.
180
181
182epilog
183^^^^^^
184
185Some programs like to display additional description of the program after the
186description of the arguments. Such text can be specified using the ``epilog=``
187argument to ArgumentParser::
188
189 >>> parser = argparse.ArgumentParser(
190 ... description='A foo that bars',
191 ... epilog="And that's how you'd foo a bar")
192 >>> parser.print_help()
193 usage: argparse.py [-h]
194
195 A foo that bars
196
197 optional arguments:
198 -h, --help show this help message and exit
199
200 And that's how you'd foo a bar
201
202As with the description_ argument, the ``epilog=`` text is by default
203line-wrapped, but this behavior can be adjusted with the formatter_class_
204argument to ArgumentParser.
205
206
207add_help
208^^^^^^^^
209
210By default, ArgumentParser objects add a ``-h/--help`` option which simply
211displays the parser's help message. For example, consider a file named
212``myprogram.py`` containing the following code::
213
214 import argparse
215 parser = argparse.ArgumentParser()
216 parser.add_argument('--foo', help='foo help')
217 args = parser.parse_args()
218
219If ``-h`` or ``--help`` is supplied is at the command-line, the ArgumentParser
220help will be printed::
221
222 $ python myprogram.py --help
223 usage: myprogram.py [-h] [--foo FOO]
224
225 optional arguments:
226 -h, --help show this help message and exit
227 --foo FOO foo help
228
229Occasionally, it may be useful to disable the addition of this help option.
230This can be achieved by passing ``False`` as the ``add_help=`` argument to
231ArgumentParser::
232
233 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
234 >>> parser.add_argument('--foo', help='foo help')
235 >>> parser.print_help()
236 usage: PROG [--foo FOO]
237
238 optional arguments:
239 --foo FOO foo help
240
241
242prefix_chars
243^^^^^^^^^^^^
244
245Most command-line options will use ``'-'`` as the prefix, e.g. ``-f/--foo``.
246Parsers that need to support additional prefix characters, e.g. for options
247like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
248to the ArgumentParser constructor::
249
250 >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
251 >>> parser.add_argument('+f')
252 >>> parser.add_argument('++bar')
253 >>> parser.parse_args('+f X ++bar Y'.split())
254 Namespace(bar='Y', f='X')
255
256The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
257characters that does not include ``'-'`` will cause ``-f/--foo`` options to be
258disallowed.
259
260
261fromfile_prefix_chars
262^^^^^^^^^^^^^^^^^^^^^
263
264Sometimes, e.g. for particularly long argument lists, it may make sense to
265keep the list of arguments in a file rather than typing it out at the command
266line. If the ``fromfile_prefix_chars=`` argument is given to the ArgumentParser
267constructor, then arguments that start with any of the specified characters
268will be treated as files, and will be replaced by the arguments they contain.
269For example::
270
271 >>> open('args.txt', 'w').write('-f\nbar')
272 >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
273 >>> parser.add_argument('-f')
274 >>> parser.parse_args(['-f', 'foo', '@args.txt'])
275 Namespace(f='bar')
276
277Arguments read from a file must by default be one per line (but see also
278:meth:`convert_arg_line_to_args`) and are treated as if they were in the same
279place as the original file referencing argument on the command line. So in the
280example above, the expression ``['-f', 'foo', '@args.txt']`` is considered
281equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.
282
283The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
284arguments will never be treated as file references.
285
286argument_default
287^^^^^^^^^^^^^^^^
288
289Generally, argument defaults are specified either by passing a default to
290:meth:`add_argument` or by calling the :meth:`set_defaults` methods with a
291specific set of name-value pairs. Sometimes however, it may be useful to
292specify a single parser-wide default for arguments. This can be accomplished by
293passing the ``argument_default=`` keyword argument to ArgumentParser. For
294example, to globally suppress attribute creation on :meth:`parse_args` calls,
295we supply ``argument_default=SUPPRESS``::
296
297 >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
298 >>> parser.add_argument('--foo')
299 >>> parser.add_argument('bar', nargs='?')
300 >>> parser.parse_args(['--foo', '1', 'BAR'])
301 Namespace(bar='BAR', foo='1')
302 >>> parser.parse_args([])
303 Namespace()
304
305
306parents
307^^^^^^^
308
309Sometimes, several parsers share a common set of arguments. Rather than
310repeating the definitions of these arguments, you can define a single parser
311with all the shared arguments and then use the ``parents=`` argument to
312ArgumentParser to have these "inherited". The ``parents=`` argument takes a
313list of ArgumentParser objects, collects all the positional and optional
314actions from them, and adds these actions to the ArgumentParser object being
315constructed::
316
317 >>> parent_parser = argparse.ArgumentParser(add_help=False)
318 >>> parent_parser.add_argument('--parent', type=int)
319
320 >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
321 >>> foo_parser.add_argument('foo')
322 >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
323 Namespace(foo='XXX', parent=2)
324
325 >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
326 >>> bar_parser.add_argument('--bar')
327 >>> bar_parser.parse_args(['--bar', 'YYY'])
328 Namespace(bar='YYY', parent=None)
329
330Note that most parent parsers will specify ``add_help=False``. Otherwise, the
331ArgumentParser will see two ``-h/--help`` options (one in the parent and one in
332the child) and raise an error.
333
334
335formatter_class
336^^^^^^^^^^^^^^^
337
338ArgumentParser objects allow the help formatting to be customized by specifying
339an alternate formatting class. Currently, there are three such classes:
340``argparse.RawDescriptionHelpFormatter``, ``argparse.RawTextHelpFormatter`` and
341``argparse.ArgumentDefaultsHelpFormatter``. The first two allow more control
342over how textual descriptions are displayed, while the last automatically adds
343information about argument default values.
344
345By default, ArgumentParser objects line-wrap the description_ and epilog_ texts
346in command-line help messages::
347
348 >>> parser = argparse.ArgumentParser(
349 ... prog='PROG',
350 ... description='''this description
351 ... was indented weird
352 ... but that is okay''',
353 ... epilog='''
354 ... likewise for this epilog whose whitespace will
355 ... be cleaned up and whose words will be wrapped
356 ... across a couple lines''')
357 >>> parser.print_help()
358 usage: PROG [-h]
359
360 this description was indented weird but that is okay
361
362 optional arguments:
363 -h, --help show this help message and exit
364
365 likewise for this epilog whose whitespace will be cleaned up and whose words
366 will be wrapped across a couple lines
367
368When you have description_ and epilog_ that is already correctly formatted and
369should not be line-wrapped, you can indicate this by passing
370``argparse.RawDescriptionHelpFormatter`` as the ``formatter_class=`` argument
371to ArgumentParser::
372
373 >>> parser = argparse.ArgumentParser(
374 ... prog='PROG',
375 ... formatter_class=argparse.RawDescriptionHelpFormatter,
376 ... description=textwrap.dedent('''\
377 ... Please do not mess up this text!
378 ... --------------------------------
379 ... I have indented it
380 ... exactly the way
381 ... I want it
382 ... '''))
383 >>> parser.print_help()
384 usage: PROG [-h]
385
386 Please do not mess up this text!
387 --------------------------------
388 I have indented it
389 exactly the way
390 I want it
391
392 optional arguments:
393 -h, --help show this help message and exit
394
395If you want to maintain whitespace for all sorts of help text (including
396argument descriptions), you can use ``argparse.RawTextHelpFormatter``.
397
398The other formatter class available,
399``argparse.ArgumentDefaultsHelpFormatter``, will add information about the
400default value of each of the arguments::
401
402 >>> parser = argparse.ArgumentParser(
403 ... prog='PROG',
404 ... formatter_class=argparse.ArgumentDefaultsHelpFormatter)
405 >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
406 >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
407 >>> parser.print_help()
408 usage: PROG [-h] [--foo FOO] [bar [bar ...]]
409
410 positional arguments:
411 bar BAR! (default: [1, 2, 3])
412
413 optional arguments:
414 -h, --help show this help message and exit
415 --foo FOO FOO! (default: 42)
416
417
418conflict_handler
419^^^^^^^^^^^^^^^^
420
421ArgumentParser objects do not allow two actions with the same option string.
422By default, ArgumentParser objects will raise an exception if you try to create
423an argument with an option string that is already in use::
424
425 >>> parser = argparse.ArgumentParser(prog='PROG')
426 >>> parser.add_argument('-f', '--foo', help='old foo help')
427 >>> parser.add_argument('--foo', help='new foo help')
428 Traceback (most recent call last):
429 ..
430 ArgumentError: argument --foo: conflicting option string(s): --foo
431
432Sometimes (e.g. when using parents_) it may be useful to simply override any
433older arguments with the same option string. To get this behavior, the value
434``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
435ArgumentParser::
436
437 >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
438 >>> parser.add_argument('-f', '--foo', help='old foo help')
439 >>> parser.add_argument('--foo', help='new foo help')
440 >>> parser.print_help()
441 usage: PROG [-h] [-f FOO] [--foo FOO]
442
443 optional arguments:
444 -h, --help show this help message and exit
445 -f FOO old foo help
446 --foo FOO new foo help
447
448Note that ArgumentParser objects only remove an action if all of its option
449strings are overridden. So, in the example above, the old ``-f/--foo`` action
450is retained as the ``-f`` action, because only the ``--foo`` option string was
451overridden.
452
453
454prog
455^^^^
456
457By default, ArgumentParser objects use ``sys.argv[0]`` to determine how to
458display the name of the program in help messages. This default is almost always
459what you want because it will make the help messages match what your users have
460typed at the command line. For example, consider a file named ``myprogram.py``
461with the following code::
462
463 import argparse
464 parser = argparse.ArgumentParser()
465 parser.add_argument('--foo', help='foo help')
466 args = parser.parse_args()
467
468The help for this program will display ``myprogram.py`` as the program name
469(regardless of where the program was invoked from)::
470
471 $ python myprogram.py --help
472 usage: myprogram.py [-h] [--foo FOO]
473
474 optional arguments:
475 -h, --help show this help message and exit
476 --foo FOO foo help
477 $ cd ..
478 $ python subdir\myprogram.py --help
479 usage: myprogram.py [-h] [--foo FOO]
480
481 optional arguments:
482 -h, --help show this help message and exit
483 --foo FOO foo help
484
485To change this default behavior, another value can be supplied using the
486``prog=`` argument to ArgumentParser::
487
488 >>> parser = argparse.ArgumentParser(prog='myprogram')
489 >>> parser.print_help()
490 usage: myprogram [-h]
491
492 optional arguments:
493 -h, --help show this help message and exit
494
495Note that the program name, whether determined from ``sys.argv[0]`` or from the
496``prog=`` argument, is available to help messages using the ``%(prog)s`` format
497specifier.
498
499::
500
501 >>> parser = argparse.ArgumentParser(prog='myprogram')
502 >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
503 >>> parser.print_help()
504 usage: myprogram [-h] [--foo FOO]
505
506 optional arguments:
507 -h, --help show this help message and exit
508 --foo FOO foo of the myprogram program
509
510
511usage
512^^^^^
513
514By default, ArgumentParser objects calculate the usage message from the
515arguments it contains::
516
517 >>> parser = argparse.ArgumentParser(prog='PROG')
518 >>> parser.add_argument('--foo', nargs='?', help='foo help')
519 >>> parser.add_argument('bar', nargs='+', help='bar help')
520 >>> parser.print_help()
521 usage: PROG [-h] [--foo [FOO]] bar [bar ...]
522
523 positional arguments:
524 bar bar help
525
526 optional arguments:
527 -h, --help show this help message and exit
528 --foo [FOO] foo help
529
530If the default usage message is not appropriate for your application, you can
531supply your own usage message using the ``usage=`` keyword argument to
532ArgumentParser::
533
534 >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
535 >>> parser.add_argument('--foo', nargs='?', help='foo help')
536 >>> parser.add_argument('bar', nargs='+', help='bar help')
537 >>> parser.print_help()
538 usage: PROG [options]
539
540 positional arguments:
541 bar bar help
542
543 optional arguments:
544 -h, --help show this help message and exit
545 --foo [FOO] foo help
546
547Note you can use the ``%(prog)s`` format specifier to fill in the program name
548in your usage messages.
549
550
551The add_argument() method
552-------------------------
553
554.. method:: add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest])
555
556 Define how a single command line argument should be parsed. Each parameter
557 has its own more detailed description below, but in short they are:
558
559 * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
560 or ``-f, --foo``
561
562 * action_ - The basic type of action to be taken when this argument is
563 encountered at the command-line.
564
565 * nargs_ - The number of command-line arguments that should be consumed.
566
567 * const_ - A constant value required by some action_ and nargs_ selections.
568
569 * default_ - The value produced if the argument is absent from the
570 command-line.
571
572 * type_ - The type to which the command-line arg should be converted.
573
574 * choices_ - A container of the allowable values for the argument.
575
576 * required_ - Whether or not the command-line option may be omitted
577 (optionals only).
578
579 * help_ - A brief description of what the argument does.
580
581 * metavar_ - A name for the argument in usage messages.
582
583 * dest_ - The name of the attribute to be added to the object returned by
584 :meth:`parse_args`.
585
586 The following sections describe how each of these are used.
587
588name or flags
589^^^^^^^^^^^^^
590
591The :meth:`add_argument` method needs to know whether you're expecting an
592optional argument, e.g. ``-f`` or ``--foo``, or a positional argument, e.g. a
593list of filenames. The first arguments passed to :meth:`add_argument` must
594therefore be either a series of flags, or a simple argument name. For example,
595an optional argument could be created like::
596
597 >>> parser.add_argument('-f', '--foo')
598
599while a positional argument could be created like::
600
601 >>> parser.add_argument('bar')
602
603When :meth:`parse_args` is called, optional arguments will be identified by the
604``-`` prefix, and the remaining arguments will be assumed to be positional::
605
606 >>> parser = argparse.ArgumentParser(prog='PROG')
607 >>> parser.add_argument('-f', '--foo')
608 >>> parser.add_argument('bar')
609 >>> parser.parse_args(['BAR'])
610 Namespace(bar='BAR', foo=None)
611 >>> parser.parse_args(['BAR', '--foo', 'FOO'])
612 Namespace(bar='BAR', foo='FOO')
613 >>> parser.parse_args(['--foo', 'FOO'])
614 usage: PROG [-h] [-f FOO] bar
615 PROG: error: too few arguments
616
617action
618^^^^^^
619
620:class:`ArgumentParser` objects associate command-line args with actions. These
621actions can do just about anything with the command-line args associated with
622them, though most actions simply add an attribute to the object returned by
623:meth:`parse_args`. When you specify a new argument using the
624:meth:`add_argument` method, you can indicate how the command-line args should
625be handled by specifying the ``action`` keyword argument. The supported actions
626are:
627
628* ``'store'`` - This just stores the argument's value. This is the default
629 action. For example::
630
631 >>> parser = argparse.ArgumentParser()
632 >>> parser.add_argument('--foo')
633 >>> parser.parse_args('--foo 1'.split())
634 Namespace(foo='1')
635
636* ``'store_const'`` - This stores the value specified by the const_ keyword
637 argument. Note that the const_ keyword argument defaults to ``None``, so
638 you'll almost always need to provide a value for it. The ``'store_const'``
639 action is most commonly used with optional arguments that specify some sort
640 of flag. For example::
641
642 >>> parser = argparse.ArgumentParser()
643 >>> parser.add_argument('--foo', action='store_const', const=42)
644 >>> parser.parse_args('--foo'.split())
645 Namespace(foo=42)
646
647* ``'store_true'`` and ``'store_false'`` - These store the values ``True`` and
648 ``False`` respectively. These are basically special cases of
649 ``'store_const'``. For example::
650
651 >>> parser = argparse.ArgumentParser()
652 >>> parser.add_argument('--foo', action='store_true')
653 >>> parser.add_argument('--bar', action='store_false')
654 >>> parser.parse_args('--foo --bar'.split())
655 Namespace(bar=False, foo=True)
656
657* ``'append'`` - This stores a list, and appends each argument value to the
658 list. This is useful when you want to allow an option to be specified
659 multiple times. Example usage::
660
661 >>> parser = argparse.ArgumentParser()
662 >>> parser.add_argument('--foo', action='append')
663 >>> parser.parse_args('--foo 1 --foo 2'.split())
664 Namespace(foo=['1', '2'])
665
666* ``'append_const'`` - This stores a list, and appends the value specified by
667 the const_ keyword argument to the list. Note that the const_ keyword
668 argument defaults to ``None``, so you'll almost always need to provide a
669 value for it. The ``'append_const'`` action is typically useful when you
670 want multiple arguments to store constants to the same list, for example::
671
672 >>> parser = argparse.ArgumentParser()
673 >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
674 >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
675 >>> parser.parse_args('--str --int'.split())
676 Namespace(types=[<type 'str'>, <type 'int'>])
677
678* ``'version'`` - This expects a ``version=`` keyword argument in the
679 :meth:`add_argument` call, and prints version information and exits when
680 invoked.
681
682 >>> import argparse
683 >>> parser = argparse.ArgumentParser(prog='PROG')
684 >>> parser.add_argument('-v', '--version', action='version', version='%(prog)s 2.0')
685 >>> parser.parse_args(['-v'])
686 PROG 2.0
687
688You can also specify an arbitrary action by passing an object that implements
689the Action API. The easiest way to do this is to extend ``argparse.Action``,
690supplying an appropriate ``__call__`` method. The ``__call__`` method accepts
691four parameters:
692
693* ``parser`` - The ArgumentParser object which contains this action.
694
695* ``namespace`` - The namespace object that will be returned by
696 :meth:`parse_args`. Most actions add an attribute to this object.
697
698* ``values`` - The associated command-line args, with any type-conversions
699 applied. (Type-conversions are specified with the type_ keyword argument to
700 :meth:`add_argument`.
701
702* ``option_string`` - The option string that was used to invoke this action.
703 The ``option_string`` argument is optional, and will be absent if the action
704 is associated with a positional argument.
705
706So for example::
707
708 >>> class FooAction(argparse.Action):
709 ... def __call__(self, parser, namespace, values, option_string=None):
710 ... print '%r %r %r' % (namespace, values, option_string)
711 ... setattr(namespace, self.dest, values)
712 ...
713 >>> parser = argparse.ArgumentParser()
714 >>> parser.add_argument('--foo', action=FooAction)
715 >>> parser.add_argument('bar', action=FooAction)
716 >>> args = parser.parse_args('1 --foo 2'.split())
717 Namespace(bar=None, foo=None) '1' None
718 Namespace(bar='1', foo=None) '2' '--foo'
719 >>> args
720 Namespace(bar='1', foo='2')
721
722
723nargs
724^^^^^
725
726ArgumentParser objects usually associate a single command-line argument with a
727single action to be taken. In the situations where you'd like to associate a
728different number of command-line arguments with a single action, you can use
729the ``nargs`` keyword argument to :meth:`add_argument`. The supported values
730are:
731
732* N (an integer). N args from the command-line will be gathered together into
733 a list. For example::
734
735 >>> parser = argparse.ArgumentParser()
736 >>> parser.add_argument('--foo', nargs=2)
737 >>> parser.add_argument('bar', nargs=1)
738 >>> parser.parse_args('c --foo a b'.split())
739 Namespace(bar=['c'], foo=['a', 'b'])
740
741 Note that ``nargs=1`` produces a list of one item. This is different from
742 the default, in which the item is produced by itself.
743
744* ``'?'``. One arg will be consumed from the command-line if possible, and
745 produced as a single item. If no command-line arg is present, the value from
746 default_ will be produced. Note that for optional arguments, there is an
747 additional case - the option string is present but not followed by a
748 command-line arg. In this case the value from const_ will be produced. Some
749 examples to illustrate this::
750
751 >>> parser = argparse.ArgumentParser()
752 >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
753 >>> parser.add_argument('bar', nargs='?', default='d')
754 >>> parser.parse_args('XX --foo YY'.split())
755 Namespace(bar='XX', foo='YY')
756 >>> parser.parse_args('XX --foo'.split())
757 Namespace(bar='XX', foo='c')
758 >>> parser.parse_args(''.split())
759 Namespace(bar='d', foo='d')
760
761 One of the more common uses of ``nargs='?'`` is to allow optional input and
762 output files::
763
764 >>> parser = argparse.ArgumentParser()
765 >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
766 >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
767 >>> parser.parse_args(['input.txt', 'output.txt'])
768 Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>, outfile=<open file 'output.txt', mode 'w' at 0x...>)
769 >>> parser.parse_args([])
770 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>, outfile=<open file '<stdout>', mode 'w' at 0x...>)
771
772* ``'*'``. All command-line args present are gathered into a list. Note that
773 it generally doesn't make much sense to have more than one positional
774 argument with ``nargs='*'``, but multiple optional arguments with
775 ``nargs='*'`` is possible. For example::
776
777 >>> parser = argparse.ArgumentParser()
778 >>> parser.add_argument('--foo', nargs='*')
779 >>> parser.add_argument('--bar', nargs='*')
780 >>> parser.add_argument('baz', nargs='*')
781 >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
782 Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])
783
784* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
785 list. Additionally, an error message will be generated if there wasn't at
786 least one command-line arg present. For example::
787
788 >>> parser = argparse.ArgumentParser(prog='PROG')
789 >>> parser.add_argument('foo', nargs='+')
790 >>> parser.parse_args('a b'.split())
791 Namespace(foo=['a', 'b'])
792 >>> parser.parse_args(''.split())
793 usage: PROG [-h] foo [foo ...]
794 PROG: error: too few arguments
795
796If the ``nargs`` keyword argument is not provided, the number of args consumed
797is determined by the action_. Generally this means a single command-line arg
798will be consumed and a single item (not a list) will be produced.
799
800
801const
802^^^^^
803
804The ``const`` argument of :meth:`add_argument` is used to hold constant values
805that are not read from the command line but are required for the various
806ArgumentParser actions. The two most common uses of it are:
807
808* When :meth:`add_argument` is called with ``action='store_const'`` or
809 ``action='append_const'``. These actions add the ``const`` value to one of
810 the attributes of the object returned by :meth:`parse_args`. See the action_
811 description for examples.
812
813* When :meth:`add_argument` is called with option strings (like ``-f`` or
814 ``--foo``) and ``nargs='?'``. This creates an optional argument that can be
815 followed by zero or one command-line args. When parsing the command-line, if
816 the option string is encountered with no command-line arg following it, the
817 value of ``const`` will be assumed instead. See the nargs_ description for
818 examples.
819
820The ``const`` keyword argument defaults to ``None``.
821
822
823default
824^^^^^^^
825
826All optional arguments and some positional arguments may be omitted at the
827command-line. The ``default`` keyword argument of :meth:`add_argument`, whose
828value defaults to ``None``, specifies what value should be used if the
829command-line arg is not present. For optional arguments, the ``default`` value
830is used when the option string was not present at the command line::
831
832 >>> parser = argparse.ArgumentParser()
833 >>> parser.add_argument('--foo', default=42)
834 >>> parser.parse_args('--foo 2'.split())
835 Namespace(foo='2')
836 >>> parser.parse_args(''.split())
837 Namespace(foo=42)
838
839For positional arguments with nargs_ ``='?'`` or ``'*'``, the ``default`` value
840is used when no command-line arg was present::
841
842 >>> parser = argparse.ArgumentParser()
843 >>> parser.add_argument('foo', nargs='?', default=42)
844 >>> parser.parse_args('a'.split())
845 Namespace(foo='a')
846 >>> parser.parse_args(''.split())
847 Namespace(foo=42)
848
849
850If you don't want to see an attribute when an option was not present at the
851command line, you can supply ``default=argparse.SUPPRESS``::
852
853 >>> parser = argparse.ArgumentParser()
854 >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
855 >>> parser.parse_args([])
856 Namespace()
857 >>> parser.parse_args(['--foo', '1'])
858 Namespace(foo='1')
859
860
861type
862^^^^
863
864By default, ArgumentParser objects read command-line args in as simple strings.
865However, quite often the command-line string should instead be interpreted as
866another type, e.g. ``float``, ``int`` or ``file``. The ``type`` keyword
867argument of :meth:`add_argument` allows any necessary type-checking and
868type-conversions to be performed. Many common builtin types can be used
869directly as the value of the ``type`` argument::
870
871 >>> parser = argparse.ArgumentParser()
872 >>> parser.add_argument('foo', type=int)
873 >>> parser.add_argument('bar', type=file)
874 >>> parser.parse_args('2 temp.txt'.split())
875 Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
876
877To ease the use of various types of files, the argparse module provides the
878factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
879``file`` object. For example, ``FileType('w')`` can be used to create a
880writable file::
881
882 >>> parser = argparse.ArgumentParser()
883 >>> parser.add_argument('bar', type=argparse.FileType('w'))
884 >>> parser.parse_args(['out.txt'])
885 Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
886
887If you need to do some special type-checking or type-conversions, you can
888provide your own types by passing to ``type=`` a callable that takes a single
889string argument and returns the type-converted value::
890
891 >>> def perfect_square(string):
892 ... value = int(string)
893 ... sqrt = math.sqrt(value)
894 ... if sqrt != int(sqrt):
895 ... msg = "%r is not a perfect square" % string
896 ... raise argparse.ArgumentTypeError(msg)
897 ... return value
898 ...
899 >>> parser = argparse.ArgumentParser(prog='PROG')
900 >>> parser.add_argument('foo', type=perfect_square)
901 >>> parser.parse_args('9'.split())
902 Namespace(foo=9)
903 >>> parser.parse_args('7'.split())
904 usage: PROG [-h] foo
905 PROG: error: argument foo: '7' is not a perfect square
906
907Note that if your type-checking function is just checking for a particular set
908of values, it may be more convenient to use the choices_ keyword argument::
909
910 >>> parser = argparse.ArgumentParser(prog='PROG')
911 >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
912 >>> parser.parse_args('7'.split())
913 Namespace(foo=7)
914 >>> parser.parse_args('11'.split())
915 usage: PROG [-h] {5,6,7,8,9}
916 PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)
917
918See the choices_ section for more details.
919
920
921choices
922^^^^^^^
923
924Some command-line args should be selected from a restricted set of values.
925ArgumentParser objects can be told about such sets of values by passing a
926container object as the ``choices`` keyword argument to :meth:`add_argument`.
927When the command-line is parsed with :meth:`parse_args`, arg values will be
928checked, and an error message will be displayed if the arg was not one of the
929acceptable values::
930
931 >>> parser = argparse.ArgumentParser(prog='PROG')
932 >>> parser.add_argument('foo', choices='abc')
933 >>> parser.parse_args('c'.split())
934 Namespace(foo='c')
935 >>> parser.parse_args('X'.split())
936 usage: PROG [-h] {a,b,c}
937 PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
938
939Note that inclusion in the ``choices`` container is checked after any type_
940conversions have been performed, so the type of the objects in the ``choices``
941container should match the type_ specified::
942
943 >>> parser = argparse.ArgumentParser(prog='PROG')
944 >>> parser.add_argument('foo', type=complex, choices=[1, 1j])
945 >>> parser.parse_args('1j'.split())
946 Namespace(foo=1j)
947 >>> parser.parse_args('-- -4'.split())
948 usage: PROG [-h] {1,1j}
949 PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
950
951Any object that supports the ``in`` operator can be passed as the ``choices``
952value, so ``dict`` objects, ``set`` objects, custom containers, etc. are all
953supported.
954
955
956required
957^^^^^^^^
958
959In general, the argparse module assumes that flags like ``-f`` and ``--bar``
960indicate *optional* arguments, which can always be omitted at the command-line.
961To change this behavior, i.e. to make an option *required*, the value ``True``
962should be specified for the ``required=`` keyword argument to
963:meth:`add_argument`::
964
965 >>> parser = argparse.ArgumentParser()
966 >>> parser.add_argument('--foo', required=True)
967 >>> parser.parse_args(['--foo', 'BAR'])
968 Namespace(foo='BAR')
969 >>> parser.parse_args([])
970 usage: argparse.py [-h] [--foo FOO]
971 argparse.py: error: option --foo is required
972
973As the example shows, if an option is marked as ``required``, :meth:`parse_args`
974will report an error if that option is not present at the command line.
975
976**Warning:** Required options are generally considered bad form - normal users
977expect *options* to be *optional*. You should avoid the use of required options
978whenever possible.
979
980
981help
982^^^^
983
984A great command-line interface isn't worth anything if your users can't figure
985out which option does what. So for the end-users, ``help`` is probably the
986most important argument to include in your :meth:`add_argument` calls. The
987``help`` value should be a string containing a brief description of what the
988argument specifies. When a user requests help (usually by using ``-h`` or
989``--help`` at the command-line), these ``help`` descriptions will be displayed
990with each argument::
991
992 >>> parser = argparse.ArgumentParser(prog='frobble')
993 >>> parser.add_argument('--foo', action='store_true',
994 ... help='foo the bars before frobbling')
995 >>> parser.add_argument('bar', nargs='+',
996 ... help='one of the bars to be frobbled')
997 >>> parser.parse_args('-h'.split())
998 usage: frobble [-h] [--foo] bar [bar ...]
999
1000 positional arguments:
1001 bar one of the bars to be frobbled
1002
1003 optional arguments:
1004 -h, --help show this help message and exit
1005 --foo foo the bars before frobbling
1006
1007The ``help`` strings can include various format specifiers to avoid repetition
1008of things like the program name or the argument default_. The available
1009specifiers include the program name, ``%(prog)s`` and most keyword arguments to
1010:meth:`add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
1011
1012 >>> parser = argparse.ArgumentParser(prog='frobble')
1013 >>> parser.add_argument('bar', nargs='?', type=int, default=42,
1014 ... help='the bar to %(prog)s (default: %(default)s)')
1015 >>> parser.print_help()
1016 usage: frobble [-h] [bar]
1017
1018 positional arguments:
1019 bar the bar to frobble (default: 42)
1020
1021 optional arguments:
1022 -h, --help show this help message and exit
1023
1024
1025metavar
1026^^^^^^^
1027
1028When ArgumentParser objects generate help messages, they need some way to refer
1029to each expected argument. By default, ArgumentParser objects use the dest_
1030value as the "name" of each object. By default, for positional argument
1031actions, the dest_ value is used directly, and for optional argument actions,
1032the dest_ value is uppercased. So if we have a single positional argument with
1033``dest='bar'``, that argument will be referred to as ``bar``. And if we have a
1034single optional argument ``--foo`` that should be followed by a single
1035command-line arg, that arg will be referred to as ``FOO``. You can see this
1036behavior in the example below::
1037
1038 >>> parser = argparse.ArgumentParser()
1039 >>> parser.add_argument('--foo')
1040 >>> parser.add_argument('bar')
1041 >>> parser.parse_args('X --foo Y'.split())
1042 Namespace(bar='X', foo='Y')
1043 >>> parser.print_help()
1044 usage: [-h] [--foo FOO] bar
1045
1046 positional arguments:
1047 bar
1048
1049 optional arguments:
1050 -h, --help show this help message and exit
1051 --foo FOO
1052
1053If you would like to provide a different name for your argument in help
1054messages, you can supply a value for the ``metavar`` keyword argument to
1055:meth:`add_argument`::
1056
1057 >>> parser = argparse.ArgumentParser()
1058 >>> parser.add_argument('--foo', metavar='YYY')
1059 >>> parser.add_argument('bar', metavar='XXX')
1060 >>> parser.parse_args('X --foo Y'.split())
1061 Namespace(bar='X', foo='Y')
1062 >>> parser.print_help()
1063 usage: [-h] [--foo YYY] XXX
1064
1065 positional arguments:
1066 XXX
1067
1068 optional arguments:
1069 -h, --help show this help message and exit
1070 --foo YYY
1071
1072Note that ``metavar`` only changes the *displayed* name - the name of the
1073attribute on the :meth:`parse_args` object is still determined by the dest_
1074value.
1075
1076Different values of ``nargs`` may cause the metavar to be used multiple times.
1077If you'd like to specify a different display name for each of the arguments,
1078you can provide a tuple to ``metavar``::
1079
1080 >>> parser = argparse.ArgumentParser(prog='PROG')
1081 >>> parser.add_argument('-x', nargs=2)
1082 >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
1083 >>> parser.print_help()
1084 usage: PROG [-h] [-x X X] [--foo bar baz]
1085
1086 optional arguments:
1087 -h, --help show this help message and exit
1088 -x X X
1089 --foo bar baz
1090
1091
1092dest
1093^^^^
1094
1095Most ArgumentParser actions add some value as an attribute of the object
1096returned by :meth:`parse_args`. The name of this attribute is determined by the
1097``dest`` keyword argument of :meth:`add_argument`. For positional argument
1098actions, ``dest`` is normally supplied as the first argument to
1099:meth:`add_argument`::
1100
1101 >>> parser = argparse.ArgumentParser()
1102 >>> parser.add_argument('bar')
1103 >>> parser.parse_args('XXX'.split())
1104 Namespace(bar='XXX')
1105
1106For optional argument actions, the value of ``dest`` is normally inferred from
1107the option strings. ArgumentParser objects generate the value of ``dest`` by
1108taking the first long option string and stripping away the initial ``'--'``
1109string. If no long option strings were supplied, ``dest`` will be derived from
1110the first short option string by stripping the initial ``'-'`` character. Any
1111internal ``'-'`` characters will be converted to ``'_'`` characters to make
1112sure the string is a valid attribute name. The examples below illustrate this
1113behavior::
1114
1115 >>> parser = argparse.ArgumentParser()
1116 >>> parser.add_argument('-f', '--foo-bar', '--foo')
1117 >>> parser.add_argument('-x', '-y')
1118 >>> parser.parse_args('-f 1 -x 2'.split())
1119 Namespace(foo_bar='1', x='2')
1120 >>> parser.parse_args('--foo 1 -y 2'.split())
1121 Namespace(foo_bar='1', x='2')
1122
1123If you would like to use a different attribute name from the one automatically
1124inferred by the ArgumentParser, you can supply it with an explicit ``dest``
1125parameter::
1126
1127 >>> parser = argparse.ArgumentParser()
1128 >>> parser.add_argument('--foo', dest='bar')
1129 >>> parser.parse_args('--foo XXX'.split())
1130 Namespace(bar='XXX')
1131
1132
1133The parse_args() method
1134-----------------------
1135
1136.. method:: parse_args([args], [namespace])
1137
1138 Convert the strings to objects and assign them as attributes of the
1139 namespace. Return the populated namespace.
1140
1141 Previous calls to :meth:`add_argument` determine exactly what objects are
1142 created and how they are assigned. See the documentation for
1143 :meth:`add_argument` for details.
1144
1145 By default, the arg strings are taken from ``sys.argv``, and a new empty
1146 ``Namespace`` object is created for the attributes.
1147
1148Option value syntax
1149^^^^^^^^^^^^^^^^^^^
1150
1151The :meth:`parse_args` method supports several ways of specifying the value of
1152an option (if it takes one). In the simplest case, the option and its value are
1153passed as two separate arguments::
1154
1155 >>> parser = argparse.ArgumentParser(prog='PROG')
1156 >>> parser.add_argument('-x')
1157 >>> parser.add_argument('--foo')
1158 >>> parser.parse_args('-x X'.split())
1159 Namespace(foo=None, x='X')
1160 >>> parser.parse_args('--foo FOO'.split())
1161 Namespace(foo='FOO', x=None)
1162
1163For long options (options with names longer than a single character), you may
1164also pass the option and value as a single command line argument, using ``=``
1165to separate them::
1166
1167 >>> parser.parse_args('--foo=FOO'.split())
1168 Namespace(foo='FOO', x=None)
1169
1170For short options (options only one character long), you may simply concatenate
1171the option and its value::
1172
1173 >>> parser.parse_args('-xX'.split())
1174 Namespace(foo=None, x='X')
1175
1176You can also combine several short options together, using only a single ``-``
1177prefix, as long as only the last option (or none of them) requires a value::
1178
1179 >>> parser = argparse.ArgumentParser(prog='PROG')
1180 >>> parser.add_argument('-x', action='store_true')
1181 >>> parser.add_argument('-y', action='store_true')
1182 >>> parser.add_argument('-z')
1183 >>> parser.parse_args('-xyzZ'.split())
1184 Namespace(x=True, y=True, z='Z')
1185
1186
1187Invalid arguments
1188^^^^^^^^^^^^^^^^^
1189
1190While parsing the command-line, ``parse_args`` checks for a variety of errors,
1191including ambiguous options, invalid types, invalid options, wrong number of
1192positional arguments, etc. When it encounters such an error, it exits and
1193prints the error along with a usage message::
1194
1195 >>> parser = argparse.ArgumentParser(prog='PROG')
1196 >>> parser.add_argument('--foo', type=int)
1197 >>> parser.add_argument('bar', nargs='?')
1198
1199 >>> # invalid type
1200 >>> parser.parse_args(['--foo', 'spam'])
1201 usage: PROG [-h] [--foo FOO] [bar]
1202 PROG: error: argument --foo: invalid int value: 'spam'
1203
1204 >>> # invalid option
1205 >>> parser.parse_args(['--bar'])
1206 usage: PROG [-h] [--foo FOO] [bar]
1207 PROG: error: no such option: --bar
1208
1209 >>> # wrong number of arguments
1210 >>> parser.parse_args(['spam', 'badger'])
1211 usage: PROG [-h] [--foo FOO] [bar]
1212 PROG: error: extra arguments found: badger
1213
1214
1215Arguments containing ``"-"``
1216^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1217
1218The ``parse_args`` method attempts to give errors whenever the user has clearly
1219made a mistake, but some situations are inherently ambiguous. For example, the
1220command-line arg ``'-1'`` could either be an attempt to specify an option or an
1221attempt to provide a positional argument. The ``parse_args`` method is cautious
1222here: positional arguments may only begin with ``'-'`` if they look like
1223negative numbers and there are no options in the parser that look like negative
1224numbers::
1225
1226 >>> parser = argparse.ArgumentParser(prog='PROG')
1227 >>> parser.add_argument('-x')
1228 >>> parser.add_argument('foo', nargs='?')
1229
1230 >>> # no negative number options, so -1 is a positional argument
1231 >>> parser.parse_args(['-x', '-1'])
1232 Namespace(foo=None, x='-1')
1233
1234 >>> # no negative number options, so -1 and -5 are positional arguments
1235 >>> parser.parse_args(['-x', '-1', '-5'])
1236 Namespace(foo='-5', x='-1')
1237
1238 >>> parser = argparse.ArgumentParser(prog='PROG')
1239 >>> parser.add_argument('-1', dest='one')
1240 >>> parser.add_argument('foo', nargs='?')
1241
1242 >>> # negative number options present, so -1 is an option
1243 >>> parser.parse_args(['-1', 'X'])
1244 Namespace(foo=None, one='X')
1245
1246 >>> # negative number options present, so -2 is an option
1247 >>> parser.parse_args(['-2'])
1248 usage: PROG [-h] [-1 ONE] [foo]
1249 PROG: error: no such option: -2
1250
1251 >>> # negative number options present, so both -1s are options
1252 >>> parser.parse_args(['-1', '-1'])
1253 usage: PROG [-h] [-1 ONE] [foo]
1254 PROG: error: argument -1: expected one argument
1255
1256If you have positional arguments that must begin with ``'-'`` and don't look
1257like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
1258``parse_args`` that everything after that is a positional argument::
1259
1260 >>> parser.parse_args(['--', '-f'])
1261 Namespace(foo='-f', one=None)
1262
1263
1264Argument abbreviations
1265^^^^^^^^^^^^^^^^^^^^^^
1266
1267The :meth:`parse_args` method allows you to abbreviate long options if the
1268abbreviation is unambiguous::
1269
1270 >>> parser = argparse.ArgumentParser(prog='PROG')
1271 >>> parser.add_argument('-bacon')
1272 >>> parser.add_argument('-badger')
1273 >>> parser.parse_args('-bac MMM'.split())
1274 Namespace(bacon='MMM', badger=None)
1275 >>> parser.parse_args('-bad WOOD'.split())
1276 Namespace(bacon=None, badger='WOOD')
1277 >>> parser.parse_args('-ba BA'.split())
1278 usage: PROG [-h] [-bacon BACON] [-badger BADGER]
1279 PROG: error: ambiguous option: -ba could match -badger, -bacon
1280
1281As you can see above, you will get an error if you pick a prefix that could
1282refer to more than one option.
1283
1284
1285Beyond ``sys.argv``
1286^^^^^^^^^^^^^^^^^^^
1287
1288Sometimes it may be useful to have an ArgumentParser parse args other than
1289those of ``sys.argv``. This can be accomplished by passing a list of strings
1290to ``parse_args``. You may have noticed that the examples in the argparse
1291documentation have made heavy use of this calling style - it is much easier
1292to use at the interactive prompt::
1293
1294 >>> parser = argparse.ArgumentParser()
1295 >>> parser.add_argument(
1296 ... 'integers', metavar='int', type=int, choices=xrange(10),
1297 ... nargs='+', help='an integer in the range 0..9')
1298 >>> parser.add_argument(
1299 ... '--sum', dest='accumulate', action='store_const', const=sum,
1300 ... default=max, help='sum the integers (default: find the max)')
1301 >>> parser.parse_args(['1', '2', '3', '4'])
1302 Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
1303 >>> parser.parse_args('1 2 3 4 --sum'.split())
1304 Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])
1305
1306
1307Custom namespaces
1308^^^^^^^^^^^^^^^^^
1309
1310It may also be useful to have an ArgumentParser assign attributes to an already
1311existing object, rather than the newly-created Namespace object that is
1312normally used. This can be achieved by specifying the ``namespace=`` keyword
1313argument::
1314
1315 >>> class C(object):
1316 ... pass
1317 ...
1318 >>> c = C()
1319 >>> parser = argparse.ArgumentParser()
1320 >>> parser.add_argument('--foo')
1321 >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
1322 >>> c.foo
1323 'BAR'
1324
1325
1326Other utilities
1327---------------
1328
1329Sub-commands
1330^^^^^^^^^^^^
1331
1332.. method:: add_subparsers()
1333
1334 A lot of programs split up their functionality into a number of
1335 sub-commands, for example, the ``svn`` program can invoke sub-commands like
1336 ``svn checkout``, ``svn update``, ``svn commit``, etc. Splitting up
1337 functionality this way can be a particularly good idea when a program
1338 performs several different functions which require different kinds of
1339 command-line arguments. ArgumentParser objects support the creation of such
1340 sub-commands with the :meth:`add_subparsers` method. The
1341 :meth:`add_subparsers` method is normally called with no arguments and
1342 returns an special action object. This object has a single method,
1343 ``add_parser``, which takes a command name and any ArgumentParser
1344 constructor arguments, and returns an ArgumentParser object that can be
1345 modified as usual.
1346
1347 Some example usage::
1348
1349 >>> # create the top-level parser
1350 >>> parser = argparse.ArgumentParser(prog='PROG')
1351 >>> parser.add_argument('--foo', action='store_true', help='foo help')
1352 >>> subparsers = parser.add_subparsers(help='sub-command help')
1353 >>>
1354 >>> # create the parser for the "a" command
1355 >>> parser_a = subparsers.add_parser('a', help='a help')
1356 >>> parser_a.add_argument('bar', type=int, help='bar help')
1357 >>>
1358 >>> # create the parser for the "b" command
1359 >>> parser_b = subparsers.add_parser('b', help='b help')
1360 >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
1361 >>>
1362 >>> # parse some arg lists
1363 >>> parser.parse_args(['a', '12'])
1364 Namespace(bar=12, foo=False)
1365 >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
1366 Namespace(baz='Z', foo=True)
1367
1368 Note that the object returned by :meth:`parse_args` will only contain
1369 attributes for the main parser and the subparser that was selected by the
1370 command line (and not any other subparsers). So in the example above, when
1371 the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes
1372 are present, and when the ``"b"`` command is specified, only the ``foo`` and
1373 ``baz`` attributes are present.
1374
1375 Similarly, when a help message is requested from a subparser, only the help
1376 for that particular parser will be printed. The help message will not
1377 include parent parser or sibling parser messages. (You can however supply a
1378 help message for each subparser command by suppling the ``help=`` argument
1379 to ``add_parser`` as above.)
1380
1381 ::
1382
1383 >>> parser.parse_args(['--help'])
1384 usage: PROG [-h] [--foo] {a,b} ...
1385
1386 positional arguments:
1387 {a,b} sub-command help
1388 a a help
1389 b b help
1390
1391 optional arguments:
1392 -h, --help show this help message and exit
1393 --foo foo help
1394
1395 >>> parser.parse_args(['a', '--help'])
1396 usage: PROG a [-h] bar
1397
1398 positional arguments:
1399 bar bar help
1400
1401 optional arguments:
1402 -h, --help show this help message and exit
1403
1404 >>> parser.parse_args(['b', '--help'])
1405 usage: PROG b [-h] [--baz {X,Y,Z}]
1406
1407 optional arguments:
1408 -h, --help show this help message and exit
1409 --baz {X,Y,Z} baz help
1410
1411 The :meth:`add_subparsers` method also supports ``title`` and
1412 ``description`` keyword arguments. When either is present, the subparser's
1413 commands will appear in their own group in the help output. For example::
1414
1415 >>> parser = argparse.ArgumentParser()
1416 >>> subparsers = parser.add_subparsers(title='subcommands',
1417 ... description='valid subcommands',
1418 ... help='additional help')
1419 >>> subparsers.add_parser('foo')
1420 >>> subparsers.add_parser('bar')
1421 >>> parser.parse_args(['-h'])
1422 usage: [-h] {foo,bar} ...
1423
1424 optional arguments:
1425 -h, --help show this help message and exit
1426
1427 subcommands:
1428 valid subcommands
1429
1430 {foo,bar} additional help
1431
1432
1433 One particularly effective way of handling sub-commands is to combine the
1434 use of the :meth:`add_subparsers` method with calls to :meth:`set_defaults`
1435 so that each subparser knows which Python function it should execute. For
1436 example::
1437
1438 >>> # sub-command functions
1439 >>> def foo(args):
1440 ... print args.x * args.y
1441 ...
1442 >>> def bar(args):
1443 ... print '((%s))' % args.z
1444 ...
1445 >>> # create the top-level parser
1446 >>> parser = argparse.ArgumentParser()
1447 >>> subparsers = parser.add_subparsers()
1448 >>>
1449 >>> # create the parser for the "foo" command
1450 >>> parser_foo = subparsers.add_parser('foo')
1451 >>> parser_foo.add_argument('-x', type=int, default=1)
1452 >>> parser_foo.add_argument('y', type=float)
1453 >>> parser_foo.set_defaults(func=foo)
1454 >>>
1455 >>> # create the parser for the "bar" command
1456 >>> parser_bar = subparsers.add_parser('bar')
1457 >>> parser_bar.add_argument('z')
1458 >>> parser_bar.set_defaults(func=bar)
1459 >>>
1460 >>> # parse the args and call whatever function was selected
1461 >>> args = parser.parse_args('foo 1 -x 2'.split())
1462 >>> args.func(args)
1463 2.0
1464 >>>
1465 >>> # parse the args and call whatever function was selected
1466 >>> args = parser.parse_args('bar XYZYX'.split())
1467 >>> args.func(args)
1468 ((XYZYX))
1469
1470 This way, you can let :meth:`parse_args` do all the work for you, and then
1471 just call the appropriate function after the argument parsing is complete.
1472 Associating functions with actions like this is typically the easiest way
1473 to handle the different actions for each of your subparsers. However, if you
1474 find it necessary to check the name of the subparser that was invoked, you
1475 can always provide a ``dest`` keyword argument to the :meth:`add_subparsers`
1476 call::
1477
1478 >>> parser = argparse.ArgumentParser()
1479 >>> subparsers = parser.add_subparsers(dest='subparser_name')
1480 >>> subparser1 = subparsers.add_parser('1')
1481 >>> subparser1.add_argument('-x')
1482 >>> subparser2 = subparsers.add_parser('2')
1483 >>> subparser2.add_argument('y')
1484 >>> parser.parse_args(['2', 'frobble'])
1485 Namespace(subparser_name='2', y='frobble')
1486
1487
1488FileType objects
1489^^^^^^^^^^^^^^^^
1490
1491.. class:: FileType(mode='r', bufsize=None)
1492
1493 The :class:`FileType` factory creates objects that can be passed to the type
1494 argument of :meth:`add_argument`. Arguments that have :class:`FileType`
1495 objects as their type will open command-line args as files with the
1496 requested modes and buffer sizes:
1497
1498 >>> parser = argparse.ArgumentParser()
1499 >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
1500 >>> parser.parse_args(['--output', 'out'])
1501 Namespace(output=<open file 'out', mode 'wb' at 0x...>)
1502
1503 FileType objects understand the pseudo-argument ``'-'`` and automatically
1504 convert this into ``sys.stdin`` for readable :class:`FileType` objects and
1505 ``sys.stdout`` for writable :class:`FileType` objects:
1506
1507 >>> parser = argparse.ArgumentParser()
1508 >>> parser.add_argument('infile', type=argparse.FileType('r'))
1509 >>> parser.parse_args(['-'])
1510 Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
1511
1512
1513Argument groups
1514^^^^^^^^^^^^^^^
1515
1516.. method:: add_argument_group([title], [description])
1517
1518 By default, ArgumentParser objects group command-line arguments into
1519 "positional arguments" and "optional arguments" when displaying help
1520 messages. When there is a better conceptual grouping of arguments than this
1521 default one, appropriate groups can be created using the
1522 :meth:`add_argument_group` method::
1523
1524 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1525 >>> group = parser.add_argument_group('group')
1526 >>> group.add_argument('--foo', help='foo help')
1527 >>> group.add_argument('bar', help='bar help')
1528 >>> parser.print_help()
1529 usage: PROG [--foo FOO] bar
1530
1531 group:
1532 bar bar help
1533 --foo FOO foo help
1534
1535 The :meth:`add_argument_group` method returns an argument group object which
1536 has an :meth:`add_argument` method just like a regular ArgumentParser
1537 objects. When an argument is added to the group, the parser treats it just
1538 like a normal argument, but displays the argument in a separate group for
1539 help messages. The :meth:`add_argument_group` method accepts ``title`` and
1540 ``description`` arguments which can be used to customize this display::
1541
1542 >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
1543 >>> group1 = parser.add_argument_group('group1', 'group1 description')
1544 >>> group1.add_argument('foo', help='foo help')
1545 >>> group2 = parser.add_argument_group('group2', 'group2 description')
1546 >>> group2.add_argument('--bar', help='bar help')
1547 >>> parser.print_help()
1548 usage: PROG [--bar BAR] foo
1549
1550 group1:
1551 group1 description
1552
1553 foo foo help
1554
1555 group2:
1556 group2 description
1557
1558 --bar BAR bar help
1559
1560 Note that any arguments not in your user defined groups will end up back in
1561 the usual "positional arguments" and "optional arguments" sections.
1562
1563
1564Mutual exclusion
1565^^^^^^^^^^^^^^^^
1566
1567.. method:: add_mutually_exclusive_group([required=False])
1568
1569 Sometimes, you need to make sure that only one of a couple different options
1570 is specified on the command line. You can create groups of such mutually
1571 exclusive arguments using the :meth:`add_mutually_exclusive_group` method.
1572 When :func:`parse_args` is called, argparse will make sure that only one of
1573 the arguments in the mutually exclusive group was present on the command
1574 line::
1575
1576 >>> parser = argparse.ArgumentParser(prog='PROG')
1577 >>> group = parser.add_mutually_exclusive_group()
1578 >>> group.add_argument('--foo', action='store_true')
1579 >>> group.add_argument('--bar', action='store_false')
1580 >>> parser.parse_args(['--foo'])
1581 Namespace(bar=True, foo=True)
1582 >>> parser.parse_args(['--bar'])
1583 Namespace(bar=False, foo=False)
1584 >>> parser.parse_args(['--foo', '--bar'])
1585 usage: PROG [-h] [--foo | --bar]
1586 PROG: error: argument --bar: not allowed with argument --foo
1587
1588 The :meth:`add_mutually_exclusive_group` method also accepts a ``required``
1589 argument, to indicate that at least one of the mutually exclusive arguments
1590 is required::
1591
1592 >>> parser = argparse.ArgumentParser(prog='PROG')
1593 >>> group = parser.add_mutually_exclusive_group(required=True)
1594 >>> group.add_argument('--foo', action='store_true')
1595 >>> group.add_argument('--bar', action='store_false')
1596 >>> parser.parse_args([])
1597 usage: PROG [-h] (--foo | --bar)
1598 PROG: error: one of the arguments --foo --bar is required
1599
1600 Note that currently mutually exclusive argument groups do not support the
1601 ``title`` and ``description`` arguments of :meth:`add_argument_group`. This
1602 may change in the future however, so you are *strongly* recommended to
1603 specify ``required`` as a keyword argument if you use it.
1604
1605
1606Parser defaults
1607^^^^^^^^^^^^^^^
1608
1609.. method:: set_defaults(**kwargs)
1610
1611 Most of the time, the attributes of the object returned by
1612 :meth:`parse_args` will be fully determined by inspecting the command-line
1613 args and the argument actions described in your :meth:`add_argument` calls.
1614 However, sometimes it may be useful to add some additional attributes that
1615 are determined without any inspection of the command-line. The
1616 :meth:`set_defaults` method allows you to do this::
1617
1618 >>> parser = argparse.ArgumentParser()
1619 >>> parser.add_argument('foo', type=int)
1620 >>> parser.set_defaults(bar=42, baz='badger')
1621 >>> parser.parse_args(['736'])
1622 Namespace(bar=42, baz='badger', foo=736)
1623
1624 Note that parser-level defaults always override argument-level defaults. So
1625 if you set a parser-level default for a name that matches an argument, the
1626 old argument default will no longer be used::
1627
1628 >>> parser = argparse.ArgumentParser()
1629 >>> parser.add_argument('--foo', default='bar')
1630 >>> parser.set_defaults(foo='spam')
1631 >>> parser.parse_args([])
1632 Namespace(foo='spam')
1633
1634 Parser-level defaults can be particularly useful when you're working with
1635 multiple parsers. See the :meth:`add_subparsers` method for an example of
1636 this type.
1637
1638.. method:: get_default(dest)
1639
1640 Get the default value for a namespace attribute, as set by either
1641 :meth:`add_argument` or by :meth:`set_defaults`::
1642
1643 >>> parser = argparse.ArgumentParser()
1644 >>> parser.add_argument('--foo', default='badger')
1645 >>> parser.get_default('foo')
1646 'badger'
1647
1648
1649Printing help
1650^^^^^^^^^^^^^
1651
1652In most typical applications, :meth:`parse_args` will take care of formatting
1653and printing any usage or error messages. However, should you want to format or
1654print these on your own, several methods are available:
1655
1656.. method:: print_usage([file]):
1657
1658 Print a brief description of how the :class:`ArgumentParser` should be
1659 invoked on the command line. If ``file`` is not present, ``sys.stderr`` is
1660 assumed.
1661
1662.. method:: print_help([file]):
1663
1664 Print a help message, including the program usage and information about the
1665 arguments registered with the :class:`ArgumentParser`. If ``file`` is not
1666 present, ``sys.stderr`` is assumed.
1667
1668There are also variants of these methods that simply return a string instead of
1669printing it:
1670
1671.. method:: format_usage():
1672
1673 Return a string containing a brief description of how the
1674 :class:`ArgumentParser` should be invoked on the command line.
1675
1676.. method:: format_help():
1677
1678 Return a string containing a help message, including the program usage and
1679 information about the arguments registered with the :class:`ArgumentParser`.
1680
1681
1682
1683Partial parsing
1684^^^^^^^^^^^^^^^
1685
1686.. method:: parse_known_args([args], [namespace])
1687
1688Sometimes a script may only parse a few of the command line arguments, passing
1689the remaining arguments on to another script or program. In these cases, the
1690:meth:`parse_known_args` method can be useful. It works much like
1691:meth:`parse_args` except that it does not produce an error when extra
1692arguments are present. Instead, it returns a two item tuple containing the
1693populated namespace and the list of remaining argument strings.
1694
1695::
1696
1697 >>> parser = argparse.ArgumentParser()
1698 >>> parser.add_argument('--foo', action='store_true')
1699 >>> parser.add_argument('bar')
1700 >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
1701 (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])
1702
1703
1704Customizing file parsing
1705^^^^^^^^^^^^^^^^^^^^^^^^
1706
1707.. method:: convert_arg_line_to_args(arg_line)
1708
1709 Arguments that are read from a file (see the ``fromfile_prefix_chars``
1710 keyword argument to the :class:`ArgumentParser` constructor) are read one
1711 argument per line. If you need fancier parsing, then you can subclass the
1712 :class:`ArgumentParser` and override the :meth:`convert_arg_line_to_args`
1713 method.
1714
1715 This method takes a single argument ``arg_line`` which is a string read from
1716 the argument file. It returns a list of arguments parsed from this string.
1717 The method is called once per line read from the argument file, in order.
1718
1719 A useful override of this method is one that treats each space-separated
1720 word as an argument::
1721
1722 def convert_arg_line_to_args(self, arg_line):
1723 for arg in arg_line.split():
1724 if not arg.strip():
1725 continue
1726 yield arg
1727
1728
1729Upgrading optparse code
1730-----------------------
1731
1732Originally, the argparse module had attempted to maintain compatibility with
1733 optparse. However, optparse was difficult to extend transparently,
1734 particularly with the changes required to support the new ``nargs=``
1735 specifiers and better usage messges. When most everything in optparse had
1736 either been copy-pasted over or monkey-patched, it no longer seemed practical
1737 to try to maintain the backwards compatibility.
1738
1739A partial upgrade path from optparse to argparse:
1740
1741* Replace all ``add_option()`` calls with :meth:`add_argument` calls.
1742
1743* Replace ``options, args = parser.parse_args()`` with
1744 ``args = parser.parse_args()`` and add additional :meth:`add_argument` calls
1745 for the positional arguments.
1746
1747* Replace callback actions and the ``callback_*`` keyword arguments with
1748 ``type`` or ``action`` arguments.
1749
1750* Replace string names for ``type`` keyword arguments with the corresponding
1751 type objects (e.g. int, float, complex, etc).
1752
1753* Replace ``Values`` with ``Namespace`` and ``OptionError/OptionValueError``
1754 with ``ArgumentError``.
1755
1756* Replace strings with implicit arguments such as ``%default`` or ``%prog``
1757 with the standard python syntax to use dictionaries to format strings, that
1758 is, ``%(default)s`` and ``%(prog)s``.