In the project, especially a slightly larger project will basically use the configuration, will involve the configuration file read, configuration parameters read.
The common parsing configuration file is Configparser, and the parse command-line argument is getopt.
The parameters of getopt can be divided into two types: Long mode and short mode.
The long mode is:--arg1 arg_value on the command line.
Short mode is a common space-delimited parameter outside of the long mode.
Use the getopt.getopt () object in your program to get the parameter in the format:
opts, args = Getopt.getopt (arg_list, Shor_mode, Long_mode).
Arg_list in Python is sys.argv[1:] because we do not use filenames as parameter resolution.
In the returned result, opts is a list of parameter tuples, such as: [(--config_file, Config.ini)], and args is the argument list.
Chestnuts:
#!/usr/bin/python#-*-coding:utf-8-*-import getoptimport sysif __name__ = = ' __main__ ': long_opts = ["config_file=" , "key1=", "key2="] short_opts = "" opts, args = Getopt.getopt (sys.argv[1:], short_opts, long_opts) Config_ File = None for opt in opts: print opt[0], opt[1] print args# command line execution macbook-pro:python$ python test_getopt.py- -config_file config.ini--key1 value1--key2 value2 args1 args2--config_file config.ini--key1 value1--key2 value2[' args1 ', ' ARGS2 ']
Python uses getopt to get configuration parameters