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
1. Guide pack :
import argparse
2. Create objects :
parser = argparse.ArgumentParser()
3. Add parameter :
parser.add_argument()
4. Analytical parameters :
parser.parse_args()
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 messageusag: A string describing the purpose of the programdescription:help The text in front of the messageepilog:help Information after informationadd_help: Whether to add help informationprefix_chars: Parameter prefixes , The default is-fromfile_prefix_chars: Prefix characters , Before the file nameargument_default: Global default values for parametersconflict_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 )
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 ,argparsebuilt-in 6 Actions can be triggered when a parameter is parsed
store: Save parameter values , You may first convert the parameter value to another data type . The default action is this
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
stroe_true/store_false: Save the corresponding Boolean value , These two actions are used to implement Boolean switches
append: Save values to a list . If the parameter repeats , Save multiple values
append_const: Save a value defined in the parameter specification to a list
version: Print version information about the program , And then quitparse.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
constget , And then fromdefaultgetdest: The parameter value is saved asparse_args()The returned namespace object is thisdestA property of the parameter value . Provideddest="a", So you can go throughargs.aAccess this parameterdefault: Set the default value of the parametertype: Convert the result entered from the command line to the set typechoice: Allowed parameter valuesrequires: Whether the choicedesk: Can be used as a parameter namehelp: 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
args = parser.parse_args() # The parameters of the command line can be passed in brackets
args_ = parser.parse_args("-i=1".split("="))
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)
Send you a complete set of exclusive Python code for Valentines Day (robbery)
Today is Valentines Day , Give
物無定味適口者珍,Python3並發場景(CPU密集/IO密集)任務的並發方式的場景抉擇(多線程threading/多進程multiprocessing/協程asyncio)
原文轉載自「劉悅的技術博客」https://v3u.cn/a