Python parameter parsing optparse python
from optparse import OptionParserdef option_parser():usage = "usage: %prog [options] arg"parser = OptionParser(usage)parser.add_option("-D", dest="file_path",metavar='FILE_PATH',help="file directory ./(default : /home/firefoxbug)",default="/home/firefoxbug")parser.add_option("-G", dest="gateway",metavar='GATEWAY',help="gateway name(must)")parser.add_option("-H", dest="mysql_host",metavar='MYSQL_HOST',help="mysql ip(must)")parser.add_option("-P", dest="mysql_port",metavar='MYSQL_PORT',type="int",help='mysql port .(default:8080)',default=80)(options, args) = parser.parse_args()print parser.print_help()if len(sys.argv) == 1:parser.error("incorrect number of arguments")return (parser,options, args)
Optparse is more powerful than getopt and will automatically generate help.
Usage: parse_performance.py [options] argOptions:-h, --help show this help message and exit-D FILE_PATHfile directory .(default : /home/firefoxbug)-G GATEWAY gateway name .(must)-H MYSQL_HOSTmysql ip .(optional)-P MYSQL_PORTmysql port .(default:80)
The dest variable in parser. add_option stores the variable after the parameter and can be accessed through options. file_path. You can also use type = "int" to specify the parameter type. the default value is 'str. You can specify the default variable parameter at the end.