argparse is a library for parsing command-line options, parameters, and subcommands
Source code comes from Lib/argparse.py
Main functions:
1. Make it easy for users to write command lines
2. argparse knows how to parse these parameters from sys.argv for the parameters required by the program.
3. Aiming at the invalid parameters given to the program by the user, argparse can automatically generate help usage.
Example 1: Write a python file or function that accepts a list of integers and generates their sum or the largest number of them.
$ cat prog.py
#coding:utf-8 import argparse parser = argparse.ArgumentParser(description='some integers') parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for 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))
Then provide parameters for this file, or provide options-h.
$ python prog.py 2 3 4 5 5 $ python prog.py --sum 1 5 67 73
$ python prog.py --help usage: prog.py [-h] [--sum] N [N ...] some integers positional arguments: N an integer for accumulator optional arguments: -h, --help show this help message and exit --sum sum the integers (default: find the max) $ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] some integers positional arguments: N an integer for accumulator optional arguments: -h, --help show this help message and exit --sum sum the integers (default: find the max)
When trying to pass in a character to the program, an error will be reported
$ python prog.py a vb c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'
1. Create a parser for command-line options, etc.
The argparse.ArgumentParser creates an object that contains all the information needed to parse the command line into python data types.
argparse
Method 1: add_argument()
This method fills in the object generated by ArgumentParser, which contains information about program parameters. Generally speaking, these calls allow ArgumentParser to accept strings on the cmd command line
And turn them into objects, which will be stored and used when parse_args() is called.
For example:
parser.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for accumulator') parser.add_argument('--sum', dest='accumulate', action= 'store_const', const=sum, default=max,help='sum the integers (default: find the max)')
When parse_args() is called, two attributes are returned, integers and accumulater attributes, which accept one or more numbers.
The accumulater attribute accepts a -- sum option, which represents the function of the sum() function of the system when the command line has the -- sum option. Without the -- sum option, it represents the function of the max() function.
Parse command line parameters:
ArgumentParser parses these parameters by parse_args(), which detects the command line, converts different parameters into appropriate formats, and calls different processing methods. In most cases, when parsing parameters from the command line, a simple namespace is constructed.
In [7]: parser.parse_args(['--sum','7','10','99']) Out[7]: Namespace(accumulate=<built-in function sum>, integers=[7, 10, 99])
In scripts, parse_args() is usually called without parameters, and ArgumentParser automatically matches parameters from sys.argv on the command line
ArgumentParser Method Analysis
class argparse.ArgumentParser(prog=None, usage=None,
description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter,
prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)
All parameters need to be passed as keyword parameters.
The following is a detailed explanation of each parameter:
-
-
- Prog => sys. argv [0] This script (program) itself
- Usage => describes the details of the script (program) (read by default from the usage that created the ArgumentParser)
- Help information displayed before description => parameter (default is None)
- Help information displayed after the epilog => parameter (default is None)
- Parents => ArgumentParser method contains a list of parameters
- formatter_class => Customizable classes to help output information
- prefix_chars => Prefix for optional parameters (default is'-')
- fromfile_prefix_chars => Characters of prefix files (default is None)
- argument_default => Global default value (default is None)
- conflict_handler => Conflict resolution options (usually not required)
- add_help=> The default parser adds - h or -- help options (which are included by default)
- allow_abbrev => Allow abbreviations for long options
-
The following are examples:
prog:
By default, ArgumentParser This object uses sys.argv[0] to decide to display the help page. When you call the program itself on the command line, it will display the help information.
For example, suppose a script called myprog.py
$ vim myprog.py #!/usr/local/Cellar/pyenv/versions/3.6.1/bin/python3 #coding:utf-8 import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo',help='foo help') args = parser.parse_args() $ python myprog.py --help usage: myprog.py [-h] [--foo FOO] optional arguments: -h, --help show this help message and exit --foo FOO foo help
Another way, ArgumentParser supports prog = parameters to achieve the same effect. The code is as follows:
In [1]: import argparse In [2]: parser = argparse.ArgumentParser(prog='myprog') In [3]: parser.print_help() usage: myprog [-h] optional arguments: -h, --help show this help message and exit #Note here that the implementation of the current shell In the catalogue there should be myprog.py This document
Note that the program name, whether using sys.argv[0] or prog = method, is equivalent to using the formatting method of%(prog)s.
In [3]: parser.add_argument('--foo',help='foo of the %(prog)s program') Out[3]: _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help='foo of the %(prog)s program', metavar=None) In [4]: parser.print_help() usage: myprog [-h] [--foo FOO] optional arguments: -h, --help show this help message and exit --foo FOO foo of the myprog program
Or use usage = this method
In [2]: parser = argparse.ArgumentParser(prog='PROG',usage='%(prog)s [options]') In [3]: parser.add_argument('--foo',nargs='?',help='foo help') Out[3]: _StoreAction(option_strings=['--foo'], dest='foo', nargs='?', const=None, default=None, type=None, choices=None, help='foo help', metavar=None) In [4]: parser.add_argument('bar',nargs='+',help='bar help') Out[4]: _StoreAction(option_strings=[], dest='bar', nargs='+', const=None, default=None, type=None, choices=None, help='bar help', metavar=None) In [5]: 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
description
Most ArgumentParser instances are constructed using the parameter description = which tells you how the program works and the description information is displayed between usage and parameters.
In [1]: import argparse In [2]: parser = argparse.ArgumentParser(description=' example ') In [3]: parser.print_help() usage: ipython [-h] example optional arguments: -h, --help show this help message and exit
By default, the description will be displayed in this line and can be passed formatter_class Parameters to modify
epilog
For some programs, additional program descriptions are added to the parameter descriptions, which are displayed by default after optional argument ation descriptions.
In [4]: parser = argparse.ArgumentParser(description=' example ',epilog=' haha that is the end' ) In [5]: parser.print_help() usage: ipython [-h] example optional arguments: -h, --help show this help message and exit haha that is the end
If you want to change it, you need to adjust it. formatter_class argument modification
parents
Sometimes several parsers need to share common parameters. Instead of redefining these parameters repeatedly, use a parser that contains all the parameters, and then pass them through the parent = parameter. The parets = parameter accepts a list of ArgumentParser objects, collects all the locations and optional operations, and adds them to an ArgumentParser being constructed.
In [6]: parent_parser = argparse.ArgumentParser(add_help=False) In [7]: parent_parser.add_argument('--parent',type=int) Out[7]: _StoreAction(option_strings=['--parent'], dest='parent', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None) In [8]: foo_parser = argparse.ArgumentParser(parents=[parent_parser]) In [9]: foo_parser.add_argument('foo') Out[9]: _StoreAction(option_strings=[], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) In [10]: foo_parser.parse_args(['--parent','2','xx']) Out[10]: Namespace(foo='xx', parent=2) In [11]: bar_parser = argparse.ArgumentParser(parents=[parent_parser]) In [12]: bar_parser.add_argument('--bar') Out[12]: _StoreAction(option_strings=['--bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) In [13]: bar_parser.parse_args(['--bar','yy']) Out[13]: Namespace(bar='yy', parent=None)
In [14]: parent_parser.print_help() usage: ipython [--parent PARENT] optional arguments: --parent PARENT In [15]: foo_parser.print_help() usage: ipython [-h] [--parent PARENT] foo positional arguments: foo optional arguments: -h, --help show this help message and exit --parent PARENT In [16]: bar_parser.print_help() usage: ipython [-h] [--parent PARENT] [--bar BAR] optional arguments: -h, --help show this help message and exit --parent PARENT --bar BAR
Here, I define a parent_parser and two subclasses foo_parser and bar_parser, which explicitly specify parents=[parent_parser]
Note that many parent classes here specify add_help=False at initialization, and if not, when using - h or - help, you will see two options and trigger error
Also note that the parent parser must be fully initialized to pass to the child class via parent = and if you don't, subsequent changes to the parent parser will not be reflected in the child parser
formatter_class
ArgumentParser objects allow a customizable class to be formatted, and currently support these four classes.
class argparse.RawDescriptionHelpFormatter class argparse.RawTextHelpFormatter class argparse.ArgumentDefaultsHelpFormatter class argparse.MetavarTypeHelpFormatterAmong them, RawDescriptionHelpFormatter and RawTextHelpFormatter These two classes have more restrictions on the text display format, and by default, ArgumentParser automatically wraps description s = and epilog = in the display command-line help information.
In [1]: import argparse In [2]: parser = argparse.ArgumentParser( ...: prog='PROG', ...: description=''' that ...: is ...: a description ''', ...: epilog=''' that ...: is ...: a epilog ''') ...: In [3]: parser.print_help() usage: PROG [-h] that is a description #You can see automatic line change optional arguments: -h, --help show this help message and exit that is a epilog #You can see automatic line change
Passing formatter_class = indicates that description = and epilog = have been formatted and should not be replaced
In [4]: parser = argparse.ArgumentParser(prog='hey!', ...: formatter_class=argparse.RawDescriptionHelpFormatter, ...: description=''' let ...: us ...: do it''') ...: In [5]: parser.print_help() usage: hey! [-h] let us do it optional arguments: -h, --help show this help message and exit
RawTextHelpFormatter Leave blanks for all kinds of help information, including parameter description information.
ArgumentDefaultsHelpFormatter This class automatically adds default values for help information for each parameter
In [9]: parser = argparse.ArgumentParser( ...: prog='hey', ...: formatter_class=argparse.ArgumentDefaultsHelpFormatter) ...: In [10]: parser.add_argument('--foo',type=int,default=42,help='foo!') Out[10]: _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=42, type=<class 'int'>, choices=None, help='foo!', metavar=None) In [11]: parser.add_argument('bar',nargs='*',default=[1,2,3,4],help='bar!') Out[11]: _StoreAction(option_strings=[], dest='bar', nargs='*', const=None, default=[1, 2, 3, 4], type=None, choices=None, help='bar!', metavar=None) In [12]: parser.print_help() usage: hey [-h] [--foo FOO] [bar [bar ...]] positional arguments: bar bar! (default: [1, 2, 3, 4]) optional arguments: -h, --help show this help message and exit --foo FOO foo! (default: 42)
MetavarTypeHelpFormatter For each parameter, the type of parameter is used as the display, and the dest mode is abandoned.
In [13]: parser = argparse.ArgumentParser( ...: prog='HELP', ...: formatter_class=argparse.MetavarTypeHelpFormatter) ...: In [14]: parser.add_argument('--foo',type=int) Out[14]: _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=<class 'int'>, choices=None, help=None, metavar=None) In [15]: parser.add_argument('bar',type=float) Out[15]: _StoreAction(option_strings=[], dest='bar', nargs=None, const=None, default=None, type=<class 'float'>, choices=None, help=None, metavar=None) In [16]: parser.print_help() usage: HELP [-h] [--foo int] float positional arguments: float optional arguments: -h, --help show this help message and exit --foo int
prefix_chars
Many command-line options use the "-" current prefix, such as - h or - help. Parser can use prefix_chars to set different prefix symbols
You can use "+" or "/"
1 In [1]: import argparse 2 3 In [2]: parser = argparse.ArgumentParser(prog='PROG',prefix_chars="-+") 4 5 In [3]: parser.add_argument('+f') 6 Out[3]: _StoreAction(option_strings=['+f'], dest='f', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) 7 8 In [4]: parser.add_argument('++bar') 9 Out[4]: _StoreAction(option_strings=['++bar'], dest='bar', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None) 10 In [5]: parser.print_help() 11 12 13 14 In [5]: parser.print_help() 15 usage: PROG [-h] [+f F] [++bar BAR] 16 17 optional arguments: 18 -h, --help show this help message and exit 19 +f F 20 ++bar BAR
Preix_chars = default parameter is'-'.
fromfile_prefix_chars
In some cases, when dealing with extremely long parameter lists, it can also be supported to save the parameter list in a file.
This requires adding the fromfile_prefix_chars = option when building ArgumentParser
argument_default
Generally speaking, the parameters are specified by adding_argument() or the method of passing name-value by calling setdefaults().
Sometimes, you need to specify a separate default value for the parameter by specifying argument_default keyword parameter to ArgumentParser
For example, global creation of attributes in parse_args() can be prevented by argument_default=SUPPERSS
conflict_handler
ArgumentParser objects are not allowed to use the same option string to represent two operations. If you try to create a new parameter in an already used option, you raise an exception.
1 In [7]: parser = argparse.ArgumentParser(prog='PROG') 2 3 In [8]: parser.add_argument('-f','--foo',help='old foo help') 4 Out[8]: _StoreAction(option_strings=['-f', '--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help='old foo help', metavar=None) 5 6 In [9]: parser.add_argument('--foo',help='new foo help') 7 --------------------------------------------------------------------------- 8 ArgumentError Traceback (most recent call last)
You can use the option conflict_handler='resolve'
1 In [10]: parser = argparse.ArgumentParser(prog='PROG',conflict_handler='resolve' 2 ...: ) 3 4 In [11]: parser.add_argument('-f','--foo',help='old foo help') 5 Out[11]: _StoreAction(option_strings=['-f', '--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help='old foo help', metavar=None) 6 7 In [12]: parser.add_argument('--foo',help='new foo help') 8 Out[12]: _StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help='new foo help', metavar=None) 9 10 In [13]: parser.print_help() 11 usage: PROG [-h] [-f FOO] [--foo FOO] 12 13 optional arguments: 14 -h, --help show this help message and exit 15 -f FOO old foo help 16 --foo FOO new foo help
ArgumentParser only removes this action if all option strings are overwritten
add_help
By default, ArgumentParser objects carry parser help information when creating options
The next article introduces ArgumentParser
The add_argument() method