After the configuration , Scripts can accept command line options and parameters .argparse It is a module that provides support for parsing various parameters , You can also generate usage help information .
Create a ArgumentParser Example , Fill in certain parameters , Then you can put the optional parameters (optional argument) And position parameters (positional argument) Read it out .
Use steps
(1)import argparse Import module first
(2)parser = argparse.ArgumentParser() Create a parse object
(3)parser.add_argument() Add the command line parameters and options you want to focus on to the object
(4)parser.parse_args() To analyze
argparse.ArgumentParser() Method parameter
description - The opening text of the command line help , In most cases , We will only use this parameter
epilog - The closing text of the command line help
……
add_argument() Method parameter
name or flags - Specifies the form of the parameter , Usually write two , Short and long parameters , See the following example "-f", "–file"
Optional options , The position is not fixed , The default is optional
Fixed position options , Default is a must
nargs - Specify... After this parameter value How many , for example , We want to use -n 1 2 3 4, To set up n The value of is [1, 2, 3, 4] #parser.add_argument("-n", "–num", nargs="+", type=int) # here nargs="+" Express , If you specify -n Options , that -n It must be followed by at least one parameter ,"+" It means at least one ,"?" Represents a or 0 individual ,"*" Express 0 One or more
default - If this option does not appear on the command line , So use default Default value specified
type - If the parameter you want to pass in is of the specified type ( for example float, int And other types that can be converted from strings ), have access to #parser.add_argument("-x", type=int) .
choices - Set the range of parameter values , If choices The type in is not a string , Remember to specify type #parser.add_argument("-y", choices=['a', 'b', 'd'])
required - Usually -f Such options are optional , But if required=True Then it's necessary #parser.add_argument("-z", choices=['a', 'b', 'd'], required=True)
metavar - Parameter name , Showing Only when you use help information .
help - Help for setting this option
action - The basic type of action to be taken when this argument is encountered at the command line.
【 example 】opts.py The contents are as follows ,
from argparse import ArgumentParser
def main():
parser = ArgumentParser()
parser.add_argument("indent",type=int,help="indent for report")
parser.add_argument("input_file",help="read data from this file")
parser.add_argument("-f","--file",dest="filename",help="read report to this file",metavar="FILE")
parser.add_argument("-x","--xray",help="specify xray strength factor")
parser.add_argument("-q","--quiet",action="store_false",dest="verbose",default=True,
help="don't print status messages to stdout")
args = parser.parse_args()
print("arguments:",args)
main()
explain :
line4 Create a ArgumentParser Example
line5,6 Add two position parameters indent and input_file, Parameters indent Must be able to be resolved to int Type of
explain : Positional parameters are those characters that have no prefix ( Usually "-") And must be given parameters , Is in all optional parameters ( Prefix character "-" start ) All parameters entered after parsing .
line7 Add an optional file name parameter , It can be "-f" or "--file"
line9 Last parameter "-q" With default values ( Here for True), When this parameter is not given, it will be set to the default value . Parameters action = "store_false" said , If this parameter is given , Will be False The value is stored in the target variable .
(1) Print help
[[email protected] ~]# python3 opts.py
usage: opts.py [-h] [-f FILE] [-x XRAY] [-q] indent input_file
opts.py: error: the following arguments are required: indent, input_file
[[email protected] ~]#
[[email protected] ~]#
[[email protected] ~]# python3 opts.py -h
usage: opts.py [-h] [-f FILE] [-x XRAY] [-q] indent input_file
positional arguments:
indent indent for report
input_file read data from this file
optional arguments:
-h, --help show this help message and exit
-f FILE, --file FILE read report to this file
-x XRAY, --xray XRAY specify xray strength factor
-q, --quiet don't print status messages to stdout
[[email protected] ~]#
(2) modular argparse Will return a Namespace object , Its properties include the above parameters
The following example gives the parameters -q,verbose Set to False( Corresponding action="store_false")
[[email protected] ~]# python3 opts.py -x 100 -q -f outfile 2 inputdata
arguments: Namespace(indent=2, input_file='inputdata', filename='outfile', xray='100', verbose=False)
[[email protected] ~]#
(3) The following example does not give parameters -q,verbose Set to True( Corresponding default=True)
[[email protected] ~]# python3 opts.py -x 100 -f outfile 2 inputdata
arguments: Namespace(indent=2, input_file='inputdata', filename='outfile', xray='100', verbose=True)
[[email protected] ~]#
(4) If an option does not give an argument , The value is None
For example, without optional parameters -f, be filename=None
[[email protected] ~]# python3 opts.py -x 100 2 inputdata
arguments: Namespace(indent=2, input_file='inputdata', filename=None, xray='100', verbose=True)
[[email protected] ~]#
(5) If the position parameter is not given, an error will be reported
[[email protected] ~]# python3 opts.py -x 100 -f outfile 2
usage: opts.py [-h] [-f FILE] [-x XRAY] [-q] indent input_file
opts.py: error: the following arguments are required: input_file
[[email protected] ~]#
(6) You can use a period symbol “.” Get the values of these parameters . stay opts.py Of main() Add such as down line
print("indent: ",args.indent)
print("input_file: ",args.input_file)
print("file: ",args.filename)
print("xray: ",args.xray)
print("quiet: ",args.verbose)
Be careful :xray No settings dest, Use xray that will do ; about file and quiet Set dest, You need to use the target variable name
[[email protected] ~]# python3 opts.py -x 100 -f outfile 2 inputdata
arguments: Namespace(indent=2, input_file='inputdata', filename='outfile', xray='100', verbose=True)
indent: 2
input_file: inputdata
file: outfile
xray: 100
quiet: True
[[email protected] ~]#
Reference material :
python3 in argparse Module details https://blog.csdn.net/qq_36653505/article/details/83788460
《Python Quick start ( The first 3 edition )》11.1.4 argparse modular