When the optparser argument of the parse()
method is specified,
the same option may be controlled by command line switches or configuration
file settings. To enable the cooperation of an option, the destination
attribute name must be the same for both the command line parser option and
the configuration parser option.
The cooperation is designed so that command line switches have priority
over configuration file settings. IMPORTANT: when adding
options to the command line parser using the add_option()
method,
omit the default argument. If it is not omitted the
configuration file setting will never be used!
Many of the arguments of the configuration file parser add_option()
method may be omitted if they were specified when the option was added to
the command line parser. When the parse()
method of the configuration
file parser is invoked they will be copied from the command line parser options
to the configuration file parser options. Sharing of arguments in the add_option()
method is not bidirectional. The following is a list of arguments
which may be shared:
Option cooperation cross reference information is added to the help text associated with both the command line and configuration file parsers. In the case of the command line option help, the information states the existance of the configuration file option. In the case of the configuration file option help, the information states the existance of the associated command line option.
For example:
# file: coop_opt.ini timeout = 10
And script:
import optparse, cfgparse o = optparse.OptionParser() c = cfgparse.ConfigParser() c.add_optparse_help_option(o) o.add_option('--timeout', type='int', help='Time between retries in seconds.') c.add_option('timeout') c.add_file('coop_opt.ini') (opts,args) = c.parse(o) print "timeout:",opts.timeout
Results in:
$ python coop_opt.py timeout: 10 $ python coop_opt.py --timeout=5 timeout: 5 $ python coop_opt.py --help usage: coop_opt.py [options] options: -h, --help show this help message and exit --cfghelp Show configuration file help and exit. --timeout=TIMEOUT Time between retries in seconds. See also 'timeout' option in configuration file help. $ python coop_opt.py --cfghelp Configuration file options: timeout=TIMEOUT Time between retries in seconds. See also '--timeout' command line switch.