Python argparse library-summary of the usage of command line parameter parsing module
1. Import the module
- import argparse first imports the python library
- parser = argparse.ArgumentParser(description="your script desciption") creates a parsing object. The description parameter can be used to insert information describing the purpose of the script, and it can be empty.
- parser.add_argument() adds the command line parameters and options you want to use to the object
- parser.parse_args() for parsing
In projects where multiple files or different languages are coordinated, python scripts often need to read parameters directly from the command line, then we need to apply the argparse library
2. Create a simple script
import argparse
parser = argparse.AugmentParser()
parser.parse_args()
3. Add parameter parser.add_argument()
positional arguments- positional parameters, mandatory by default
parser.add_argument("b")
optional arguments
-w specified short parameter
--weight specified long parameter
parser.add_argument("-w","--weight")
In this case, -v must specify the parameter value, otherwise an error will be reported. If you don't pass the parameter to -v and want to prevent the program from reporting an error, you can use:
parser.add_argument("-w","--weight", action="store_true")
type-parameter type
<font color=black size =4>默认的为str
parser.add_argument("-w","--weight", type=int, action="store_true")
choices[]-optional values
Limit the parameter value range
parser.add_argument("-w","--weight", choices=[0, 1, 2, 3, 4], type=int, action="store_true")
default-parameter default value
parser.add_argument("-w","--weight",
choices=[0, 1, 2, 3, 4],
type=int,
action="store_true",
default=0)
Program usage help
description&&help
parser = argparse.ArgumentParser(description="训练DaliNet模型")
parser.add_argument("-w","--weight",
choices=[0, 1, 2, 3, 4],
type=int,
action="store_true",
default=0,
help="存放weight的位置")
parser.parse_args()
parse_known_args() parsing
It is similar to parse_args(), but parse_known_args() will not report an error when accepting extra parameters from the command line
parser = argparse.ArgumentParser(description="训练DaliNet模型")
parser.add_argument("-w","--weight",
choices=[0, 1, 2, 3, 4],
type=int,
action="store_true",
default=0,
help="存放weight的位置")
flags, unparsed = parser.parse_known_args()
#$ python prog.py --flag_int 0.02 --double 0.03 a 1
#Namespace(flag_int=0.02)
#['--double', '0.03', 'a', '1']