3.4 Files switch

The add_optparse_files_option() method is used to set up cooperation between the command line and configuration file parsers to automatically add configuration files to the configuration file parser that were specified using a command line switch (the files are added when the parse() method is called).

add_optparse_files_option( option_group [, switches] [, dest] [, help] )

option_group is a required positional argument and must be set to an instance of the optparse module's OptionParser class or an option group of that class. The OptionParser instance must also be passed into the parse() method.

switches is an optional keyword argument and is used to set the command line switches the user can use to specify configuration files to be added to the parser. switches must be a tuple and defaults to ('--cfgfiles',) when switches is omitted.

dest is an optional string keyword argument and is used set the name of the destination attribute of the options object returned by the command line option parser. When omitted, dest defaults to 'cfgparse_files'.

help is an optional string keyword argument and is used to set the command line switch help string. When omitted a reasonable default help string is utilized.

For example:

# file: coop_files.ini
path = 192.168.0.0

And script:

# file: coop_files.py
import optparse
import cfgparse
o = optparse.OptionParser()
c = cfgparse.ConfigParser()
c.add_optparse_files_option(o)
c.add_option('path')
(opts,args) = c.parse(o)
print "Path:",opts.path

Results in:

$ python coop_files.py
ERROR: Configuration File Parser

Option: path
No valid default found.
keys=DEFAULT

$ python coop_files.py --cfgfiles=coop_files.ini
Path: 192.168.0.0