Docsity

Argparse: Biblioteka do Parsowania Argumentów Linii Poleceń w Pythonie, Publikacje z Informatyka

Toggle sidebar
bg1
argparse — Parser for command-line options, arguments and sub-commands
New in version 3.2.
Source code: Lib/argparse.py
Tutorial
This page contains the API reference information. For a more gentle introduction to Python
command-line parsing, have a look at the argparse tutorial.
The argparse module makes it easy to write user-friendly command-line interfaces. The program
defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv.
The 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:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Podgląd częściowego tekstu

Pobierz Argparse: Biblioteka do Parsowania Argumentów Linii Poleceń w Pythonie i więcej Publikacje w PDF z Informatyka tylko na Docsity!

argparse — Parser for command-line options, arguments and sub-commands New in version 3.2. Source code: Lib/argparse.py Tutorial This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the argparse tutorial. The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The 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:

$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -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: $ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10 If invalid arguments are passed in, it will issue an error: $ python 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 argparse is creating an ArgumentParser object:

parser = argparse.ArgumentParser(description='Process some integers.')

PROG: error: unrecognized arguments: --foon New in version 3.5. conflict_handler ArgumentParser objects do not allow two actions with the same option string. By default, ArgumentParser objects raise 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 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] options: -h, --help show this help message and exit -f FOO old foo help --foo FOO new foo help Note that 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.

add_help By default, ArgumentParser objects add an option which simply displays the parser’s help message. For example, consider a file named myprogram.py containing the following code: import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help') args = parser.parse_args() If -h or --help is supplied at the command line, the ArgumentParser help will be printed: $ python myprogram.py --help usage: myprogram.py [-h] [--foo FOO] options: -h, --help show this help message and exit --foo FOO foo help Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing False as the add_help= argument to ArgumentParser:

parser = argparse.ArgumentParser(prog='PROG', add_help=False) parser.add_argument('--foo', help='foo help') parser.print_help() usage: PROG [--foo FOO] options: --foo FOO foo help parser.add_argument('--foo', help='new foo help') >>> parser.print_help() usage: PROG [-h] [-f FOO] [--foo FOO] options: -h, --help show this help message and exit -f FOO old foo help --foo FOO new foo help Note that 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. add_help By default, ArgumentParser objects add an option which simply displays the parser’s help message. For example, consider a file named myprogram.py containing the following code: import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help') args = parser.parse_args() If -h or --help is supplied at the command line, the ArgumentParser help will be printed: $ python myprogram.py --help usage: myprogram.py [-h] [--foo FOO] options: -h, --help show this help message and exit --foo FOO foo help Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing False as the add_help= argument to ArgumentParser: >>> >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False) >>> parser.add_argument('--foo', help='foo help') >>> parser.print_help() usage: PROG [--foo FOO] options: --foo FOO foo help The help option is typically -h/--help. The exception to this is if the prefix_chars= is specified and does not include -, in which case -h and --help are not valid options. In this case, the first character in prefix_chars is used to prefix the help options:

name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo. action - The basic type of action to be taken when this argument is encountered at the command line. nargs - The number of command-line arguments that should be consumed. const - A constant value required by some action and nargs selections. default - The value produced if the argument is absent from the command line and if it is absent from the namespace object. type - The type to which the command-line argument should be converted. choices - A container of the allowable values for the argument. required - Whether or not the command-line option may be omitted (optionals only). help - A brief description of what the argument does. metavar - A name for the argument in usage messages. dest - The name of the attribute to be added to the object returned by parse_args(). The following sections describe how each of these are used. name or flags The add_argument() method must know whether an optional argument, like -f or --foo, or a positional argument, like a list of filenames, is expected. The first arguments passed to add_argument() must therefore be either a series of flags, or a simple argument name. For example, an optional argument could be created like:

parser.add_argument('-f', '--foo') while a positional argument could be created like:

parser.add_argument('bar') When parse_args() is called, optional arguments will be identified by the - prefix, and the remaining arguments will be assumed to be positional:

parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('-f', '--foo') parser.add_argument('bar') parser.parse_args(['BAR']) Namespace(bar='BAR', foo=None) parser.parse_args(['BAR', '--foo', 'FOO']) Namespace(bar='BAR', foo='FOO') parser.parse_args(['--foo', 'FOO']) usage: PROG [-h] [-f FOO] bar

PROG: error: the following arguments are required: bar action ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parse_args(). The action keyword argument specifies how the command-line arguments should be handled. The supplied actions are: 'store' - This just stores the argument’s value. This is the default action. For example:

parser = argparse.ArgumentParser() parser.add_argument('--foo')

parser = argparse.ArgumentParser() parser.add_argument('--str', dest='types', action='append_const', const=str) parser.add_argument('--int', dest='types', action='append_const', const=int) parser.parse_args('--str --int'.split()) Namespace(types=[<class 'str'>, <class 'int'>]) 'count' - This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels:

parser = argparse.ArgumentParser() parser.add_argument('--verbose', '-v', action='count', default=0) parser.parse_args(['-vvv']) Namespace(verbose=3) Note, the default will be None unless explicitly set to 0. 'help' - This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created. 'version' - This expects a version= keyword argument in the add_argument() call, and prints version information and exits when invoked:

import argparse parser = argparse.ArgumentParser(prog='PROG') parser.add_argument('--version', action='version', version='%(prog)s 2.0') parser.parse_args(['--version']) PROG 2. 'extend' - This stores a list, and extends each argument value to the list. Example usage:

parser = argparse.ArgumentParser() parser.add_argument("--foo", action="extend", nargs="+", type=str) parser.parse_args(["--foo", "f1", "--foo", "f2", "f3", "f4"]) Namespace(foo=['f1', 'f2', 'f3', 'f4']) New in version 3.8. You may also specify an arbitrary action by passing an Action subclass or other object that implements the same interface. The BooleanOptionalAction is available in argparse and adds support for boolean actions such as --foo and --no-foo:

import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo', action=argparse.BooleanOptionalAction) parser.parse_args(['--no-foo']) Namespace(foo=False) New in version 3.9. The recommended way to create a custom action is to extend Action, overriding the call method and optionally the init and format_usage methods. An example of a custom action:

class FooAction(argparse.Action): ... def init(self, option_strings, dest, nargs=None, **kwargs): ... if nargs is not None: ... raise ValueError("nargs not allowed") ... super().init(option_strings, dest, **kwargs) ... def call(self, parser, namespace, values, option_string=None): ... print('%r %r %r' % (namespace, values, option_string)) ... setattr(namespace, self.dest, values)

parser = argparse.ArgumentParser() parser.add_argument('--foo', nargs='?', const='c', default='d') parser.add_argument('bar', nargs='?', default='d') parser.parse_args(['XX', '--foo', 'YY']) Namespace(bar='XX', foo='YY') parser.parse_args(['XX', '--foo']) Namespace(bar='XX', foo='c') parser.parse_args([]) Namespace(bar='d', foo='d') One of the more common uses of nargs='?' is to allow optional input and output files:

parser = argparse.ArgumentParser() parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), ... default=sys.stdin) parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), ... default=sys.stdout) parser.parse_args(['input.txt', 'output.txt']) Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>, outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>) parser.parse_args([]) Namespace(infile=<_io.TextIOWrapper name='' encoding='UTF-8'>, outfile=<_io.TextIOWrapper name='' encoding='UTF-8'>) ''. All command-line arguments present are gathered into a list. Note that it generally doesn’t make much sense to have more than one positional argument with nargs='', but multiple optional usage: doors.py [-h] {1,2,3} doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3) Any container can be passed as the choices value, so list objects, set objects, and custom containers are all supported.

Use of enum.Enum is not recommended because it is difficult to control its appearance in usage, help, and error messages. Formatted choices overrides the default metavar which is normally derived from dest. This is usually what you want because the user never sees the dest parameter. If this display isn’t desirable (perhaps because there are many choices), just specify an explicit metavar.