the simple use argparse module python
Brief introduction
argparse is standard python module for parsing command line parameters and options. Argparse effect module is used to parse command line parameters.
Steps for usage
1. First, import the module
2. Then create an object to be analyzed
3. Then you have to add the command line arguments and options attention to the object, each add_argument method corresponds to a parameter you want attention or options
4. Last call parse_args ( ) method to parse; can be used after successfully resolved
1:import argparse
2:parser = argparse.ArgumentParser()
3:parser.add_argument()
4:parser.parse_args()
Basic use
The main functions of the program explained
import argparse
parser = argparse.ArgumentParser(description="程序的主要功能是...")#对程序的主要功能进行说明
parser.parse_args()
Code execution
python 1.py --help
Results of the
usage: 1.py [-h]
程序的主要功能是...
optional arguments:
-h, --help show this help message and exit
Add a location parameter
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print('参数echo的值是{}'.format(args.echo))
Code execution
python 1.py 'hello'
Results of the
参数echo的值是hello
note:
1. The above is the code to add a parameter name is stored in the 'echo' variable inside.
2. Note that to obtain the value of a variable, you need to get args object via parse_args () method.
3. Therefore, the value of the command-line information can be obtained by args object.
4. Note that due to the location parameter specified here, and that is, do not carry parameters if you execute the program, it will error
Reference: https://blog.csdn.net/weixin_41796207/article/details/80846406