01. Libraries installed
argparse Kuo is python Command line parameter parsing package , Not only can you get parameters from the user command line , You can also automatically output help content , Use import argparse
To determine whether the library has been installed , without , The installation method is also very simple , Use pip install argparse
You can install it directly .
02. Create a parameter resolution object
Before using , First you need to create a parser for parameters , Showing help It will show his description , Of course , The parameters in brackets are optional .
parse = argparse.ArgumentParser(description='description')
This generates a parse Object to be parsed .
03. Add parameter list
Add some parameters to this object , Use add_argument
Method , Its prototype is :
parse.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
04. Options name\flag\action\default\type\help
The first parameter is the flag that receives the input of the number of users , for example --path
,-y
etc. , The following options are optional , Specific for :
parse.add_argument('-y',action = 'store_false/store_ture',default = False,help = 'this is help')
The parameters in this sentence -y In existence , According to the action Medium false or true, When it doesn't exist , Default False, Such parameters are similar to a judgment ,yes or no, There is also a type of parameter that can be set to obtain the parameter type ,int、str
etc. , This type of parameter will save the user input , For the last operation , for example ;
parse.add_argument('-path',type=str,default ='c:',help = 'cd to this path')
The two parameters set above need to use parse.parse_args()
analysis , Assign a value to a variable after parsing , This variable will save all the parameters entered by the user , The specific usage is :
args = parse.parse_args()
print args
During execution, you can see that our input has been saved .
Running resultsUse -h Get help list .
Help list05. Options nargs\const\choices\required\metavar\dest
We usually need to use the above parameters , The following is only for understanding .
?
Express 1 Or 0 Parameters ,*
Express 0 One or more ,+
Means one or more .nargs = '+'
nargs = '?'
nargs = '*'
add_argument('-sex',type=str,default = 'man',choices = ['man','woman'],help = 'choice your sex')
ValueError: nargs must be '?' to supply const
Error of .error: argument -sex is required
args.Ysex
Access this parameter , If you don't specify , The default name will be used instead of .add_argument('-sex',type=str,default = 'man',choices = ['man','woman'],help = 'choice your sex',dest='Ysex')
# If not specified dest Will use -sex Medium sex Default storage ,args.sex visit .
01.click Libraries installed
click It is a parameter acquisition library developed by a third party , You can quickly modify a function as a command line , Compare with python Self contained argparse Come on , More powerful , And more at will , have access to pip install click
install .
02.click Basic use
click The command line is divided into options and parameters , The options are option, Parameter is argument, among option More functions , It encapsulates many special functions , It means optional , This parameter is optional ; and argument Indicates the parameters that must exist , It is stored in the corresponding variables in sequence , Use it directly xxx
visit .
03. Decorate a function as a command line
Used in code @click.command()
Change the function below to the command line , This way is obviously simpler .
import click
@click.command()
@click.option('-name',type = str , default = 'wwwaxlz' , help = 'input your name' , prompt = 'your name:')
def myfunc(name):
click.echo(name)
myfunc()
In the code above is option Simple usage , It includes type、default、help and prompt, among default and help And argparse identical . No more introduction , and type Aspects extend many new types , Enriches third-party libraries ,prompt Is the prompt made when this option is not entered , Let's take a look at type The content of :
except int / string / float And so on ,click Contains many new types , for example :
click.Choice(['yes','no'])
It means that you can only choose between two contents , Be careful 'C' Capitalization , Otherwise has no attribute 'choice' Error of click.option('-password',hide_input=True, confirmation_prompt=True,prompt = 'input your pwd' , help = 'password')
,hide_input
Indicates that the input content will be hidden during input , and confirmation
Indicates whether confirmation is required after input , Similar to password input in other scenarios . For passwords click There are special options ,@click.password_option()
You can complete the above content directly .import click
@click.command()
@click.option('-filen',type = click.File('rb'),prompt = 'input your filename',help = 'open file')
def myfunc(filen):
print filen.read()
myfunc()
The rb
Method to open a file , If the user does not specify this parameter at the beginning , The user will be prompted to enter .
If you only need this file name or path name , have access to :
import click
@click.command()
@click.option('-filen',type = click.Path(exists=True),prompt = 'input your filename',help = 'open file')
def myfunc(filen):
clcik.echo(filen)
myfunc()
exists=True
You can directly determine whether the path exists . Running results 04.click.argument Add fixed parameters
Use argument When adding parameters , Parameter must exist , And there's no prompt、help
Options such as , When this parameter is not selected , It will make mistakes directly :Error: Missing argument "_FILEN".
Since it is not a parameter of the option class , Then his value depends entirely on the order of declarations , Who is the first to declare , The first parameter is who .
for example :
@click.command()
@click.argument('filen',type = click.Path(exists=True))
@click.argument('myn',type = str , default = 'sks')
def myfunc(filen,myn):
print filen,myn
The supplied parameter name must be the same as the function parameter name , Only in this way can the user's command line input be correctly obtained .
Execution resultsObviously, this method does not have as many actions as the option class can complete , But it can be used in simple scripts , Minimalist .
argparse And click Do the same thing , But one is python A library of its own , One is the third-party library compiled by the great God ,argparse You can write parameters for the entire script , It doesn't need to be stated many times , and click Providing arguments to a function , The user's input is taken by the function , Each function needs to be registered first command, In particular, the package is relatively complete , Worth learning !
Python list (list) Methods sor
List of articles Method 1 :+