cpython: 09011896374d Doc/library/argparse.rst (original) (raw)

line wrap: on

line source

:mod:argparse --- Parser for command-line options, arguments and sub-commands =============================================================================== .. module:: argparse :synopsis: Command-line option and argument parsing library. .. moduleauthor:: Steven Bethard steven.bethard@gmail.com .. sectionauthor:: Steven Bethard steven.bethard@gmail.com .. versionadded:: 3.2 Source code: :source:Lib/argparse.py -------------- .. sidebar:: Tutorial This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the :ref:argparse tutorial <argparse-tutorial>. The :mod:argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and :mod:argparse will figure out how to parse those out of :data:sys.argv. The :mod:argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments. Example ------- The following code is a Python program that takes a list of integers and produces either the sum or the max:: import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() print(args.accumulate(args.integers)) Assuming the Python code above is saved into a file called prog.py, it can be run at the command line and provides useful help messages:: $ prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator optional arguments: -h, --help show this help message and exit --sum sum the integers (default: find the max) When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:: $ prog.py 1 2 3 4 4 $ prog.py 1 2 3 4 --sum 10 If invalid arguments are passed in, it will issue an error:: $ prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a' The following sections walk you through this example. Creating a parser ^^^^^^^^^^^^^^^^^ The first step in using the :mod:argparse is creating an :class:ArgumentParser object::

parser = argparse.ArgumentParser(description='Process some integers.') The :class:ArgumentParser object will hold all the information necessary to parse the command line into Python data types. Adding arguments ^^^^^^^^^^^^^^^^ Filling an :class:ArgumentParser with information about program arguments is done by making calls to the :meth:~ArgumentParser.add_argument method. Generally, these calls tell the :class:ArgumentParser how to take the strings on the command line and turn them into objects. This information is stored and used when :meth:~ArgumentParser.parse_args is called. For example:: parser.add_argument('integers', metavar='N', type=int, nargs='+', ... help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', ... const=sum, default=max, ... help='sum the integers (default: find the max)') Later, calling :meth:~ArgumentParser.parse_args will return an object with two attributes, integers and accumulate. The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the :func:sum function, if --sum was specified at the command line, or the :func:max function if it was not. Parsing arguments ^^^^^^^^^^^^^^^^^ :class:ArgumentParser parses arguments through the :meth:~ArgumentParser.parse_args method. This will inspect the command line, convert each argument to the appropriate type and then invoke the appropriate action. In most cases, this means a simple :class:Namespace object will be built up from attributes parsed out of the command line:: parser.parse_args(['--sum', '7', '-1', '42']) Namespace(accumulate=, integers=[7, -1, 42]) In a script, :meth:~ArgumentParser.parse_args will typically be called with no arguments, and the :class:ArgumentParser will automatically determine the command-line arguments from :data:sys.argv. ArgumentParser objects ---------------------- .. class:: ArgumentParser(prog=None, usage=None, description=None, [](#l133) epilog=None, parents=[], [](#l134) formatter_class=argparse.HelpFormatter, [](#l135) prefix_chars='-', fromfile_prefix_chars=None, [](#l136) argument_default=None, conflict_handler='error', [](#l137) add_help=True) Create a new :class:ArgumentParser object. Each parameter has its own more detailed description below, but in short they are:

:class:RawDescriptionHelpFormatter and :class:RawTextHelpFormatter give more control over how textual descriptions are displayed. By default, :class:ArgumentParser objects line-wrap the description_ and epilog_ texts in command-line help messages::

parser = argparse.ArgumentParser( ... prog='PROG', ... description='''this description ... was indented weird ... but that is okay''', ... epilog=''' ... likewise for this epilog whose whitespace will ... be cleaned up and whose words will be wrapped ... across a couple lines''') parser.print_help() usage: PROG [-h] this description was indented weird but that is okay optional arguments: -h, --help show this help message and exit likewise for this epilog whose whitespace will be cleaned up and whose words will be wrapped across a couple lines Passing :class:RawDescriptionHelpFormatter as formatter_class= indicates that description_ and epilog_ are already correctly formatted and should not be line-wrapped:: parser = argparse.ArgumentParser( ... prog='PROG', ... formatter_class=argparse.RawDescriptionHelpFormatter, ... description=textwrap.dedent('''[](#l414) ... Please do not mess up this text ... -------------------------------- ... I have indented it ... exactly the way ... I want it ... ''')) parser.print_help() usage: PROG [-h] Please do not mess up this text -------------------------------- I have indented it exactly the way I want it optional arguments: -h, --help show this help message and exit :class:RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions. :class:ArgumentDefaultsHelpFormatter automatically adds information about default values to each of the argument help messages:: parser = argparse.ArgumentParser( ... prog='PROG', ... formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--foo', type=int, default=42, help='FOO!') parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!') parser.print_help() usage: PROG [-h] [--foo FOO] [bar [bar ...]] positional arguments: bar BAR! (default: [1, 2, 3]) optional arguments: -h, --help show this help message and exit --foo FOO FOO! (default: 42) :class:MetavarTypeHelpFormatter uses the name of the type_ argument for each argument as the display name for its values (rather than using the dest_ as the regular formatter does):: parser = argparse.ArgumentParser( ... prog='PROG', ... formatter_class=argparse.MetavarTypeHelpFormatter) parser.add_argument('--foo', type=int) parser.add_argument('bar', type=float) parser.print_help() usage: PROG [-h] [--foo int] float positional arguments: float optional arguments: -h, --help show this help message and exit --foo int conflict_handler ^^^^^^^^^^^^^^^^ :class:ArgumentParser objects do not allow two actions with the same option string. By default, :class:ArgumentParser objects raises an exception if an attempt is made to create an argument with an option string that is already in use:: parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('-f', '--foo', help='old foo help') parser.add_argument('--foo', help='new foo help') Traceback (most recent call last): .. ArgumentError: argument --foo: conflicting option string(s): --foo Sometimes (e.g. when using parents_) it may be useful to simply override any older arguments with the same option string. To get this behavior, the value 'resolve' can be supplied to the conflict_handler= argument of :class:ArgumentParser:: parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve') parser.add_argument('-f', '--foo', help='old foo help') parser.add_argument('--foo', help='new foo help') parser.print_help() usage: PROG [-h] [-f FOO] [--foo FOO] optional arguments: -h, --help show this help message and exit -f FOO old foo help --foo FOO new foo help Note that :class:ArgumentParser objects only remove an action if all of its option strings are overridden. So, in the example above, the old -f/--foo action is retained as the -f action, because only the --foo option string was overridden. prog ^^^^ By default, :class:ArgumentParser objects uses sys.argv[0] to determine how to display the name of the program in help messages. This default is almost always desirable because it will make the help messages match how the program was invoked on the command line. For example, consider a file named myprogram.py with the following code:: import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help') args = parser.parse_args() The help for this program will display myprogram.py as the program name (regardless of where the program was invoked from):: $ python myprogram.py --help usage: myprogram.py [-h] [--foo FOO] optional arguments: -h, --help show this help message and exit --foo FOO foo help $ cd .. $ python subdir\myprogram.py --help usage: myprogram.py [-h] [--foo FOO] optional arguments: -h, --help show this help message and exit --foo FOO foo help To change this default behavior, another value can be supplied using the prog= argument to :class:ArgumentParser:: parser = argparse.ArgumentParser(prog='myprogram') parser.print_help() usage: myprogram [-h] optional arguments: -h, --help show this help message and exit Note that the program name, whether determined from sys.argv[0] or from the prog= argument, is available to help messages using the %(prog)s format specifier. :: parser = argparse.ArgumentParser(prog='myprogram') parser.add_argument('--foo', help='foo of the %(prog)s program') parser.print_help() usage: myprogram [-h] [--foo FOO] optional arguments: -h, --help show this help message and exit --foo FOO foo of the myprogram program usage ^^^^^ By default, :class:ArgumentParser calculates the usage message from the arguments it contains:: parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('--foo', nargs='?', help='foo help') parser.add_argument('bar', nargs='+', help='bar help') parser.print_help() usage: PROG [-h] [--foo [FOO]] bar [bar ...] positional arguments: bar bar help optional arguments: -h, --help show this help message and exit --foo [FOO] foo help The default message can be overridden with the usage= keyword argument:: parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') parser.add_argument('--foo', nargs='?', help='foo help') parser.add_argument('bar', nargs='+', help='bar help') parser.print_help() usage: PROG [options] positional arguments: bar bar help optional arguments: -h, --help show this help message and exit --foo [FOO] foo help The %(prog)s format specifier is available to fill in the program name in your usage messages. The add_argument() method ------------------------- .. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [](#l609) [const], [default], [type], [choices], [required], [](#l610) [help], [metavar], [dest]) Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:

>>> parser.parse_args(['a', '--help']) usage: PROG a [-h] bar positional arguments: bar bar help optional arguments: -h, --help show this help message and exit >>> parser.parse_args(['b', '--help']) usage: PROG b [-h] [--baz {X,Y,Z}] optional arguments: -h, --help show this help message and exit --baz {X,Y,Z} baz help The :meth:add_subparsers method also supports title and description keyword arguments. When either is present, the subparser's commands will appear in their own group in the help output. For example:: >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers(title='subcommands', ... description='valid subcommands', ... help='additional help') >>> subparsers.add_parser('foo') >>> subparsers.add_parser('bar') >>> parser.parse_args(['-h']) usage: [-h] {foo,bar} ... optional arguments: -h, --help show this help message and exit subcommands: valid subcommands {foo,bar} additional help Furthermore, add_parser supports an additional aliases argument, which allows multiple strings to refer to the same subparser. This example, like svn, aliases co as a shorthand for checkout:: >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers() >>> checkout = subparsers.add_parser('checkout', aliases=['co']) >>> checkout.add_argument('foo') >>> parser.parse_args(['co', 'bar']) Namespace(foo='bar') One particularly effective way of handling sub-commands is to combine the use of the :meth:add_subparsers method with calls to :meth:set_defaults so that each subparser knows which Python function it should execute. For example:: >>> # sub-command functions >>> def foo(args): ... print(args.x * args.y) ... >>> def bar(args): ... print('((%s))' % args.z) ... >>> # create the top-level parser >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers() >>> >>> # create the parser for the "foo" command >>> parser_foo = subparsers.add_parser('foo') >>> parser_foo.add_argument('-x', type=int, default=1) >>> parser_foo.add_argument('y', type=float) >>> parser_foo.set_defaults(func=foo) >>> >>> # create the parser for the "bar" command >>> parser_bar = subparsers.add_parser('bar') >>> parser_bar.add_argument('z') >>> parser_bar.set_defaults(func=bar) >>> >>> # parse the args and call whatever function was selected >>> args = parser.parse_args('foo 1 -x 2'.split()) >>> args.func(args) 2.0 >>> >>> # parse the args and call whatever function was selected >>> args = parser.parse_args('bar XYZYX'.split()) >>> args.func(args) ((XYZYX)) This way, you can let :meth:parse_args do the job of calling the appropriate function after argument parsing is complete. Associating functions with actions like this is typically the easiest way to handle the different actions for each of your subparsers. However, if it is necessary to check the name of the subparser that was invoked, the dest keyword argument to the :meth:add_subparsers call will work:: >>> parser = argparse.ArgumentParser() >>> subparsers = parser.add_subparsers(dest='subparser_name') >>> subparser1 = subparsers.add_parser('1') >>> subparser1.add_argument('-x') >>> subparser2 = subparsers.add_parser('2') >>> subparser2.add_argument('y') >>> parser.parse_args(['2', 'frobble']) Namespace(subparser_name='2', y='frobble') FileType objects ^^^^^^^^^^^^^^^^ .. class:: FileType(mode='r', bufsize=None) The :class:FileType factory creates objects that can be passed to the type argument of :meth:ArgumentParser.add_argument. Arguments that have :class:FileType objects as their type will open command-line arguments as files with the requested modes and buffer sizes:: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--output', type=argparse.FileType('wb', 0)) >>> parser.parse_args(['--output', 'out']) Namespace(output=<_io.BufferedWriter name='out'>) FileType objects understand the pseudo-argument '-' and automatically convert this into sys.stdin for readable :class:FileType objects and sys.stdout for writable :class:FileType objects:: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('infile', type=argparse.FileType('r')) >>> parser.parse_args(['-']) Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>) Argument groups ^^^^^^^^^^^^^^^ .. method:: ArgumentParser.add_argument_group(title=None, description=None) By default, :class:ArgumentParser groups command-line arguments into "positional arguments" and "optional arguments" when displaying help messages. When there is a better conceptual grouping of arguments than this default one, appropriate groups can be created using the :meth:add_argument_group method:: >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) >>> group = parser.add_argument_group('group') >>> group.add_argument('--foo', help='foo help') >>> group.add_argument('bar', help='bar help') >>> parser.print_help() usage: PROG [--foo FOO] bar group: bar bar help --foo FOO foo help The :meth:add_argument_group method returns an argument group object which has an :meth:~ArgumentParser.add_argument method just like a regular :class:ArgumentParser. When an argument is added to the group, the parser treats it just like a normal argument, but displays the argument in a separate group for help messages. The :meth:add_argument_group method accepts title and description arguments which can be used to customize this display:: >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) >>> group1 = parser.add_argument_group('group1', 'group1 description') >>> group1.add_argument('foo', help='foo help') >>> group2 = parser.add_argument_group('group2', 'group2 description') >>> group2.add_argument('--bar', help='bar help') >>> parser.print_help() usage: PROG [--bar BAR] foo group1: group1 description foo foo help group2: group2 description --bar BAR bar help Note that any arguments not in your user-defined groups will end up back in the usual "positional arguments" and "optional arguments" sections. Mutual exclusion ^^^^^^^^^^^^^^^^ .. method:: add_mutually_exclusive_group(required=False) Create a mutually exclusive group. :mod:argparse will make sure that only one of the arguments in the mutually exclusive group was present on the command line:: >>> parser = argparse.ArgumentParser(prog='PROG') >>> group = parser.add_mutually_exclusive_group() >>> group.add_argument('--foo', action='store_true') >>> group.add_argument('--bar', action='store_false') >>> parser.parse_args(['--foo']) Namespace(bar=True, foo=True) >>> parser.parse_args(['--bar']) Namespace(bar=False, foo=False) >>> parser.parse_args(['--foo', '--bar']) usage: PROG [-h] [--foo | --bar] PROG: error: argument --bar: not allowed with argument --foo The :meth:add_mutually_exclusive_group method also accepts a required argument, to indicate that at least one of the mutually exclusive arguments is required:: >>> parser = argparse.ArgumentParser(prog='PROG') >>> group = parser.add_mutually_exclusive_group(required=True) >>> group.add_argument('--foo', action='store_true') >>> group.add_argument('--bar', action='store_false') >>> parser.parse_args([]) usage: PROG [-h] (--foo | --bar) PROG: error: one of the arguments --foo --bar is required Note that currently mutually exclusive argument groups do not support the title and description arguments of :meth:~ArgumentParser.add_argument_group. Parser defaults ^^^^^^^^^^^^^^^ .. method:: ArgumentParser.set_defaults(**kwargs) Most of the time, the attributes of the object returned by :meth:parse_args will be fully determined by inspecting the command-line arguments and the argument actions. :meth:set_defaults allows some additional attributes that are determined without any inspection of the command line to be added:: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('foo', type=int) >>> parser.set_defaults(bar=42, baz='badger') >>> parser.parse_args(['736']) Namespace(bar=42, baz='badger', foo=736) Note that parser-level defaults always override argument-level defaults:: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', default='bar') >>> parser.set_defaults(foo='spam') >>> parser.parse_args([]) Namespace(foo='spam') Parser-level defaults can be particularly useful when working with multiple parsers. See the :meth:~ArgumentParser.add_subparsers method for an example of this type. .. method:: ArgumentParser.get_default(dest) Get the default value for a namespace attribute, as set by either :meth:~ArgumentParser.add_argument or by :meth:~ArgumentParser.set_defaults:: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', default='badger') >>> parser.get_default('foo') 'badger' Printing help ^^^^^^^^^^^^^ In most typical applications, :meth:~ArgumentParser.parse_args will take care of formatting and printing any usage or error messages. However, several formatting methods are available: .. method:: ArgumentParser.print_usage(file=None) Print a brief description of how the :class:ArgumentParser should be invoked on the command line. If file is None, :data:sys.stdout is assumed. .. method:: ArgumentParser.print_help(file=None) Print a help message, including the program usage and information about the arguments registered with the :class:ArgumentParser. If file is None, :data:sys.stdout is assumed. There are also variants of these methods that simply return a string instead of printing it: .. method:: ArgumentParser.format_usage() Return a string containing a brief description of how the :class:ArgumentParser should be invoked on the command line. .. method:: ArgumentParser.format_help() Return a string containing a help message, including the program usage and information about the arguments registered with the :class:ArgumentParser. Partial parsing ^^^^^^^^^^^^^^^ .. method:: ArgumentParser.parse_known_args(args=None, namespace=None) Sometimes a script may only parse a few of the command-line arguments, passing the remaining arguments on to another script or program. In these cases, the :meth:~ArgumentParser.parse_known_args method can be useful. It works much like :meth:~ArgumentParser.parse_args except that it does not produce an error when extra arguments are present. Instead, it returns a two item tuple containing the populated namespace and the list of remaining argument strings. ::

parser = argparse.ArgumentParser() parser.add_argument('--foo', action='store_true') parser.add_argument('bar') parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam']) (Namespace(bar='BAR', foo=True), ['--badger', 'spam']) Customizing file parsing ^^^^^^^^^^^^^^^^^^^^^^^^ .. method:: ArgumentParser.convert_arg_line_to_args(arg_line) Arguments that are read from a file (see the fromfile_prefix_chars keyword argument to the :class:ArgumentParser constructor) are read one argument per line. :meth:convert_arg_line_to_args can be overriden for fancier reading. This method takes a single argument arg_line which is a string read from the argument file. It returns a list of arguments parsed from this string. The method is called once per line read from the argument file, in order. A useful override of this method is one that treats each space-separated word as an argument:: def convert_arg_line_to_args(self, arg_line): for arg in arg_line.split(): if not arg.strip(): continue yield arg Exiting methods ^^^^^^^^^^^^^^^ .. method:: ArgumentParser.exit(status=0, message=None) This method terminates the program, exiting with the specified status and, if given, it prints a message before that. .. method:: ArgumentParser.error(message) This method prints a usage message including the message to the standard error and terminates the program with a status code of 2. .. _upgrading-optparse-code: Upgrading optparse code ----------------------- Originally, the :mod:argparse module had attempted to maintain compatibility with :mod:optparse. However, :mod:optparse was difficult to extend transparently, particularly with the changes required to support the new nargs= specifiers and better usage messages. When most everything in :mod:optparse had either been copy-pasted over or monkey-patched, it no longer seemed practical to try to maintain the backwards compatibility. A partial upgrade path from :mod:optparse to :mod:argparse: