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

Argparse module in Python

編輯:Python

List of articles

  • argparse Module usage
    • One 、 Concept
    • Two 、 Basics
      • 1、 Use steps
        • 1.1 General steps
        • 1.2 Create objects
        • 1.3 Add parameter
        • 1.4 Analytical parameters
    • 3、 ... and 、 Use cases

argparse Module usage

One 、 Concept

argsparse yes python Standard module for command line parsing , Built in python, No installation required . This library allows us to pass parameters into the program directly from the command line and let the program run .

Location of official documents :【https://docs.python.org/zh-cn/3/library/argparse.html】

Here we use git To demonstrate command line operation

git -h
git -version
git show

Two 、 Basics

1、 Use steps

1.1 General steps

1. Guide pack :
import argparse
2. Create objects :
parser = argparse.ArgumentParser()
3. Add parameter :
parser.add_argument()
4. Analytical parameters :
parser.parse_args()

1.2 Create objects

parser = 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)

Parameter description :

  • prog: Name of program , The default is sys.argv[0], Used in help The name of the program described in the message
  • usag: A string describing the purpose of the program
  • description:help The text in front of the message
  • epilog:help Information after information
  • add_help: Whether to add help information
  • prefix_chars: Parameter prefixes , The default is -
  • fromfile_prefix_chars: Prefix characters , Before the file name
  • argument_default: Global default values for parameters
  • conflict_hander: How to deal with conflicts , The default is to return an error “error”. also “resolve”, Intelligent conflict resolution . When the user adds two same command parameters to the program ,“error” Just report the mistake directly , Remind users . and “resolve” Will remove some or all of the repeated command parameters for the first time ( It may be short command conflicts or all conflicts )

1.3 Add parameter

add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

Parameter description :

  • name or flags: There are two kinds of parameters , Optional and positional parameters .parse_args() Runtime , Will use - To authenticate the optional parameters , The rest is the position parameter . Position parameter must be selected , Optional parameters are optional
# Optional parameters 
parser.add_argument("-f", "--foo")
# Positional arguments 
parser.add_argument("bar") # Position parameters must be input during operation 
  • action: action ,argparse built-in 6 Actions can be triggered when a parameter is parsed

    1. store: Save parameter values , You may first convert the parameter value to another data type . The default action is this

    2. store_const: Save a value defined as part of the parameter specification , Instead of a value parsed from a parameter . This is often used to implement non Boolean command line tags

    3. stroe_true/store_false: Save the corresponding Boolean value , These two actions are used to implement Boolean switches

    4. append: Save values to a list . If the parameter repeats , Save multiple values

    5. append_const: Save a value defined in the parameter specification to a list

    6. version: Print version information about the program , And then quit

parse.add_argument('--version',action = 'version',version = '%(prog)s2.0')
  • nargs: Number of parameters
    • The value can be an integer ,*( Any number of ),+( One or more )
    • First get the parameters from the command line , If not, follow const get , And then from default get
  • dest: The parameter value is saved as parse_args() The returned namespace object is this dest A property of the parameter value . Provided dest="a", So you can go through args.a Access this parameter
  • default: Set the default value of the parameter
  • type: Convert the result entered from the command line to the set type
  • choice: Allowed parameter values
  • requires: Whether the choice
  • desk: Can be used as a parameter name
  • help: Parameter command introduction

Several ways to write parameters :

python py.py -i 1 # Use spaces to separate 
python py.py --integer=1 # Long options are separated by an equal sign 
python py.py -i1 # Short options can be written together 

1.4 Analytical parameters

args = parser.parse_args() # The parameters of the command line can be passed in brackets 
args_ = parser.parse_args("-i=1".split("="))

3、 ... and 、 Use cases

We can create a template :

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = "A.L.Kun"
__file__ = "demo01.py"
__time__ = "2022/6/16 17:12"
__email__ = "[email protected]"
from typing import Callable
from functools import wraps
import sys, argparse
def terminal(param: bool = False): # Determine if you want to use command-line arguments 
def get_params(fun: Callable):
if param:
parser = argparse.ArgumentParser(description="help document")
"---------------------------------------------------------------"
# If you need to pass in parameters from the command line , Add... Here 
"---------------------------------------------------------------"
args = parser.parse_args()
else:
args = None
@wraps(fun)
def inner():
ret = fun(args) # You may need to perform other initialization operations while transferring parameters 
return ret
return inner
return get_params
@terminal() # Use decorators 
def main(args):
print(args)
if __name__ == "__main__":
main()
sys.exit(0)

Use cases , Create a program , You can connect to the mailbox SMTP service

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = "A.L.Kun"
__file__ = "demo01.py"
__time__ = "2022/6/16 17:12"
__email__ = "[email protected]"
from smtplib import SMTP
from typing import Callable
from functools import wraps
import sys, argparse
def terminal(param: bool = False):
def get_params(fun: Callable):
if param:
parser = argparse.ArgumentParser(description="help document")
"---------------------------------------------------------------"
parser.add_argument('--version', "-v", action='version', version='%(prog)s 2.0')
parser.add_argument("-u", "--username", type=str, help="Enter the SMTP server account", required=True)
parser.add_argument("-p", "--password", type=str, help="Enter the SMTP server password", required=True)
"---------------------------------------------------------------"
args = parser.parse_args()
else:
args = None
@wraps(fun)
def inner():
ret = fun(args)
return ret
return inner
return get_params
@terminal(True)
def main(args):
smtp = SMTP('smtp.qq.com')
smtp.login(args.username, args.password)
smtp.quit()
smtp.close()
if __name__ == "__main__":
main()
sys.exit(0)

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