argparse python standard library which is used to process the library of command line arguments, using substantially the following steps:
1.import argparse import module
2.parser = argparse.ArgumentParser () to create an object to be analyzed
3.parser.add_argument () to add command line parameters and options to object
4.args = parser.parse_args () parses
5.arg = args. Parameter name 1,2, ... to obtain parameters 1,2, ...
Test code:
Import argparse Parser = argparse.ArgumentParser () # Create instance # add parameters parser.add_argument ( ' F ' ) # mandatory parameters. 1 parser.add_argument ( ' -a ' , type = int) # optional parameter 2 parser.add_argument ( ' -b ' , type = STR) # optional parameter. 3 parser.add_argument ( ' -C ' , ' - C1 ' , = int type, default = 80) # optional parameters. 4 parser.add_argument ( ' --D ', = int type, default = 80) # optional parameters. 5 args = parser.parse_args () # resolution parameters Print ( " Parameter 1: {0}, the parameter 2: {1}, 3 parameters: {2}, the parameters 4 : {3}, the parameters. 5: {4} " .format (args.f, args.a, args.b, args.c1, args.d)) # obtain optional parameter values 4, need args.c1, can not be used args.c, otherwise it will be reported Attributes wrong
Test results are as follows:
Enter python temp.py, run error: Missing required parameter f
Enter python temp.py ffff, run successfully
Enter python temp.py ffff -a 10 -b 20 -c 30 -d 40, run successfully
Input python temp.py -a 10 -b 20 -c 30 -d 40 ffff, given run (mandatory parameter, a position parameter is not misplaced)
Input python temp.py ffff -b 20 --d 40 -c 30 -a 10, the optional parameter scrambled, successful operation
Input python temp.py ffff -b 20 --d 40 --c1 30 -a 10, the - c replaced --c1, successful operation