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

python_ Argparse & click Library (receiving user parameters from the command line)

編輯:Python

argparse library

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 results  

Use -h Get help list .

  Help list
adopt args.path、args.y You can operate on these two values separately , Achieve what we need .

05. Options nargs\const\choices\required\metavar\dest

We usually need to use the above parameters , The following is only for understanding .

  • nargs Indicates that this parameter receives several objects , For example, a parameter requires multiple inputs , To specify nargs, Where wildcards ? Express 1 Or 0 Parameters ,* Express 0 One or more ,+ Means one or more .
nargs = '+'
nargs = '?'
nargs = '*'
  • choices Options that represent this parameter , You can only choose from them , For example, the parameter is gender , Only from man、woman Choose from .
add_argument('-sex',type=str,default = 'man',choices = ['man','woman'],help = 'choice your sex')
  • const And nargs by ? Must appear at the same time , And when the option is selected without parameters, it will be selected by default const The content in , When there is no option, it will take default The content in . When there is no nargs When it comes to ValueError: nargs must be '?' to supply const Error of .
  • required Indicates that this parameter must exist , If set to required However, if this parameter is not included, you will be prompted :error: argument -sex is required
  • metavar Expand the written contents to the help information of the parameter , Showing help It will also be displayed .
  • dest Indicates in which variable the obtained parameters are stored , for example dest='Ysex', Indicates that it can be used 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 .

click library

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 .
  • As a third-party library , Of course, it is very convenient in some ways , for example :
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 .

    Running results

  • 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()
  • add to 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 results  

Obviously, this method does not have as many actions as the option class can complete , But it can be used in simple scripts , Minimalist .

summary

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 !


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