New configuration module - interfacing to command line options

Vinay Sajip vinay_sajip at red-dove.com
Thu Nov 4 00:29:44 CET 2004


Neal,
> 
> I believe a decent config module should at least handle both config files
> and command line options.  ENV variables are a nice touch too.
> 
Further to my earlier post, I did a bit of thinking and find it very 
easy to accommodate command line options read via optparse within the 
overall configuration framework. Consider the following hypothetical 
configuration file 'cmdline.cfg':

cmdline_values:
{
   verbose : `cmdline.verbose`
   file: `cmdline.filename`
}
other_config_items:
{
   whatever : 'you want'
}

The values of interest are those provided in the 'cmdline_values' part 
of the configuration. (You can, of course, use whatever structure you 
like - this is only an example.)

Consider the following program:

from optparse import OptionParser
from config import Config

parser = OptionParser()
parser.add_option("-f", "--file",
                 action="store", type="string", dest="filename",
                 help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                 action="store_false", dest="verbose", default=1,
                 help="don't print status messages to stdout")

(options, args) = parser.parse_args()

cfg = Config(file('cmdline.cfg'))
cfg.addNamespace(options, 'cmdline')
print "The verbose option value is %r" % cfg.cmdline_values.verbose
print "The file name is %r" %  cfg.cmdline_values.file

After parsing the command line using OptionParser, we read in the 
configuration (possibly getting the configuration file from the parsed 
options, though not in this case). We also add a namespace called 
'cmdline' which adds the parsed option settings to the configuration. 
When we later reference cfg.cmdline_values.verbose, this references 
`cmdline.verbose`, and this resolves to the 'verbose' attribute of the 
parsed-options object (added under the name 'cmdline'). The program will 
print

The verbose option value is False
The file name is 'test'

as you would expect.

N.B. I had to make a small change to the Config.addNamespace method to 
get this to work. The current release (0.3) does not have this fix, but 
the next release will.

Best regards,



Vinay Sajip



More information about the Python-list mailing list