程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Argparse module usage - based on python3.6

編輯:Python

This paper mainly aims at argparse Module to introduce
The first part , Briefly argparse The role of 、 Use scenarios
The second part , Briefly describe the trilogy used , And how to use the command line ( The specific practice is in the introduction of the use method , Will be used , Can be observed )
The third part , Focus on how to add parameters , And verify that ( Required parameters 、 Not a required parameter 、 Definition of different attributes for each parameter )
The fourth part , Make a supplementary explanation

One 、argparse brief introduction

Use scenarios : Run on the server python The program , Don't want to change the code , Instead, the parameters are directly introduced into the program through the command
effect
1) Parameter command line to parse
2) Separation of parameters and code , Convenient for parameter modification
3) Private customization , And automatically generate help documents , Use of auxiliary programs

Two 、 Basic use steps (3 A step )

1. Create objects
parser = argparse.ArgumentParser()
2. Add parameters ( Defining parameters , Here, we will expand in the third part )
parser.add_argument()
3. analysis
args = parser.parse_args()
args. Custom parameter name

In script , Usually parse_args() Will be called without parameters , and ArgumentParser Will automatically from sys.argv Determine the command line parameters in .

4. Usage mode
Input... At the terminal :python3 file name .py Required parameters Non mandatory parameters 0 Not a required parameter 0 Corresponding value Non mandatory parameters 1 Not a required parameter 1 Corresponding value ....
The following is the default -h(–help) For example :

python3 learnTest.py --help

learnTest.py To carry out py file
The results are as follows :

-h、–help: Describe the command line parameters
explain : After subsequent customization ,-h It will also be displayed

3、 ... and 、add_argument Basic use

In the use of , The main reason is that the definition of parameters involves a lot ( Parameters , Insert it into the following example to verify ),
add_argument() Method defines how to parse command line parameters
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

Each parameter is explained as follows (*: The expression is used in this article ):
name or flags - Name or list of option strings , for example foo perhaps -f, --foo.
*action - Action when the command line encounters a parameter , The default value is store.
store_const, Indicates that the assignment is const;
append, Store the encountered values as a list , That is, if the parameters are repeated, multiple values will be saved ;
append_const, Save a value defined in the parameter specification to a list ;
count, Number of storage encounters ; Besides , Can also inherit argparse.Action Custom parameter resolution ;
nargs - The number of command line parameters that should be read , It can be a specific number , Or is it ? Number , When no value is specified for Positional argument Use default, about Optional argument Use const; Or is it * Number , Express 0 Or multiple parameters ; Or is it + The sign means 1 Or multiple parameters .
const - action and nargs Required constant value .
*default - Default value when no parameter is specified .
*type - The type to which command line arguments should be converted .
*choices - A container of allowable values for parameters .
required - Optional parameters can be omitted ( Only for optional parameters ).
*help - Parameter help , When the specified as argparse.SUPPRESS Does not display help information for this parameter .
metavar - stay usage Parameter name in the description , For the required parameters, the default is the parameter name , For optional parameters, the parameter name is all uppercase by default .
dest - Parsed parameter name , By default , For optional parameters, select the longest name , Center dash to underline

(1) Add required parameters

Define parameters directly , nothing “-” perhaps “–” Represents a required parameter
help: You can fill in the definition of parameters , Help users use , Increase the readability of the program

 parser = argparse.ArgumentParser(description=' The program mainly describes argparse Use of modules ')
parser.add_argument("p0", help=" No, \"-\" perhaps \"--\", So it is a required parameter , If it is filled in, an error will be reported ")
args = parser.parse_args()
print(args.p0)


As can be seen from the figure above :
1) When adding custom parameters ,help Parameters can help display parameter information
2) When using python3 XXX.py test when :
Add... To the code p0 This parameter
When executing a command , Automatically put “test” This parameter value is assigned to p0, namely :p0 = test
3) If the required parameter values are not filled in the command , Will be an error , Tell you what you need p0 Parameters

(2) Add optional parameters

Use “-” perhaps “–” Define optional parameters
type: The type to which command line arguments should be converted , If the type is incorrect, an error will be reported

By default , If no type is specified , Will follow character string For storage

As can be seen from the picture above , When the specified type is int after , If you enter a string again, an error will be reported


The command line executed in the above figure does not define optional parameters , It can be seen from the above figure :
When optional parameters are not specified , The default is none
explain : Optional parameters are on the command line , You need to declare parameters first , Then specify the parameter value

(3) Set parameters without specific values (action)

action It can be set to “store_true” perhaps “store_false”

 parser.add_argument("-p2","-a", action="store_true")
parser.add_argument("-p3", "-b", action="store_true",default=True)
parser.add_argument("-p4", "-c", action="store_true", default=False)
parser.add_argument("-p5", "-d", action="store_false")
parser.add_argument("-p6", "-e", action="store_false", default=True)
parser.add_argument("-p7", "-f", action="store_false", default=False)
args = parser.parse_args()
print(args)

1) When executing an order , If the parameter is not set ,
Yes default Of default Value , If not, take the opposite value (action_true, Parameter values =false;action_false, Parameter values =true;)
( Say it frankly , Without parameters default work )

2) When executing an order , When parameters are passed ,
action_true Of , All for true
action_false Of , All for false
( Say it frankly , Once the parameters are passed action_true/action_false It works )

3) Add logic measurement :
In practical use , Logic can be executed by specifying parameters A, No execution logic is specified B

(4) Very short form of setting parameters

 parser.add_argument("-p8", "-parameter8", type = str,default=" Parameters 8")

“-p8”, yes "-parameter8" Very short mode , Execution instruction , The effect is the same , See the figure below for details :

(5) Add a value range for the parameter (choices)

Set up choices after , Then the parameter value can only be obtained from the set container

parser.add_argument("-p8", "-parameter8", type = str,default=" Parameters 8",choices=[" Parameters 8"," Parameters 88"," Parameters 888"])

Execute the order as follows :

Four 、 explain


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved