Application scenario:
When python develops a Window program, if it needs to realize different functions by accepting externally passed parameters at startup, it can be realized in the following ways:
1. Pass boolean parameters:
1. The library mainly used in python projects: argparse (argparse is a Python module: command line options, parameters and subcommand parsers)
2. The python code creates a parser object:
parser = argparse.Argumentparser(description = "定义一个解析器")
3. Add parsing attributes to python code:
parser.add_ageument ("isTrue","-b",action="store_true",help="传递一个布尔值",defalut = Flase)
args=paser.parse_args()
isTrue=args.isTrue
print("传递的布尔值为:"+isTrue)
4. Open the exe program compiled by Python (the python code can be converted into an exe package through pyinstaller):
For example, open the python program through the window terminal command:
or start pythonTest.exe -b
result:
Python program execution results:
Passed boolean value: true
2. In addition to passing Boolean values, other types of parameters can also be passed:
Int type:
parser.add_ageument ("intNumber", type="int", help="pass an Int data", default = 5)
Caller: start pythonTest.exe --intNumber 10
String keywords:
parser.add_ageument ("name",help="pass a name")
Caller: start pythonTest.exe --name "Zhang San"
Add_argument() method parameter description:
name or flags : A list of names or an option string, which is the first parameter of add_argument, used to match different key values corresponding to different types of parameters.
action - Indicates the action to be performed by the option
default - the value to use when the argument does not appear on the command line
dest - the location to specify the parameter
type - is the parameter type, such as int
choices - the range used to choose the input parameters. For example, choice = [1, 5, 10], which means that the input parameter can only be 1, 5 or 10
help - used to describe the function of this option, adding program parameter information to an ArgumentParser is done by calling the add_argument() method