Source code for pysteg.sql.config
#! /usr/bin/env python
## -*- coding: utf-8 -*-
## (C) 2012: Hans Georg Schaathun <georg@schaathun.net>
"""
This module defines the :class:`cp` class which is used to manage global
configuration. It should not be imported directly, instead an instance,
config, is exposed by the :mod:`pysteg.sql` package. The :class:`cp`
class decorates the :class:`OptionParser` and should be used to parse
options in scripts. Some command line options are defined to override
the config file.
"""
import optparse
import ConfigParser
import io
import os
import numpy as np
# Convert numpy warnings to exceptions.
### np.seterr( all="raise" )
defaults="""
[DEFAULT]
verbosity = 2
[sql]
url = postgres://localhost/pysteg
imageroot =
modeldir =
"""
[docs]class cp(ConfigParser.SafeConfigParser):
"""This class represents a configuration and supports option
parsing both from config files and from command line options.
The form is implemented by inheriting :class:`SafeConfigParse`
and the second by an instance of :class:`OptionParser`.
"""
def __init__(self):
ConfigParser.SafeConfigParser.__init__(self)
self.parser = optparse.OptionParser()
self.add_option("-v", "--verbosity",
help="Verbosity level", dest="verbosity" )
self.add_option("-s", "--url",
help="URL for the SQL server", dest="url" )
[docs] def add_option(self,*a,**kw):
"""Define a command line option. This is passed to the
:class:`OptionParser` class."""
return self.parser.add_option(*a,**kw)
[docs] def parse_args(self,*a,**kw):
"""Parse command line arguments. This is first passed to the
:class:`OptionParser` class before known options are interpreted
and used to override the config files."""
(opt,args) = self.parser.parse_args(*a,**kw)
self._parseOpt(opt)
return (opt,args)
[docs] def getVerbosity(self,section="DEFAULT"):
"Get the verbosity level as an integer."
return int( config.get( section, "verbosity" ) )
def _parseOpt(self,opt):
"""Interpret options. This is called by the :meth:`parse_args`
method."""
if opt.url != None:
self.set( "sql", "url", opt.url )
if opt.verbosity != None:
self.set( "DEFAULT", "verbosity", opt.verbosity )
files = [ "/etc/pystegrc", os.path.expanduser("~/.pystegrc"),
"./.pystegrc", "./pystegrc", ]
config = cp( )
config.readfp(io.BytesIO(defaults))
rl = config.read(files)
for f in rl: print "Config read from", f
if __name__ == "__main__":
(opt,args) = config.parse_args()
print config.get( "sql", "url" )
print config.get( "sql", "modeldir" )
print config.get( "DEFAULT", "verbosity" )
print config.get( "sql", "verbosity" )