from ConfigParser import ConfigParser
try:
import _winreg as winreg
except ImportError:
winreg = None
if winreg:
KILN_KEY = 'Software\\Fog Creek Software\\Kiln'
DEFAULT = 'Root'
class KilnConfig(object):
def __init__(self, filename=None):
try:
if filename:
self.filename = filename
self.file_config = ConfigParser()
self.file_config.read(self.filename)
else:
self.file_config = None
except IOError:
self.file_config = None
if not self.file_config and not winreg:
raise KilnConfigError('No config file given and cannot access registry.')
def read(self, section, option, **kwargs):
cp_section = section or DEFAULT
value = None
if self.file_config and self.file_config.has_section(cp_section) and self.file_config.has_option(cp_section, option):
value = self.file_config.get(cp_section or '', option)
elif winreg:
try:
value = self._read_reg(section, option)
except WindowsError:
value = None
if value is not None:
return value
if 'default' in kwargs:
return kwargs['default']
raise KeyError('%s\\%s does not exist in this config file.' % (section or '', option))
def _read_reg(self, section, option):
if section:
key_name = KILN_KEY + '\\' + section
else:
key_name = KILN_KEY
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name)
value, reg_type = winreg.QueryValueEx(key, option)
return value
def write(self, section, option, value):
if self.file_config:
self.file_config.add_section(section or DEFAULT)
self.file_config.set(section or DEFAULT, option, value)
self.file_config.write(open(self.filename, 'w'))
if winreg:
self._write_reg(section, option, value)
def _write_reg(self, section, option, value):
if section:
key_name = KILN_KEY + '\\' + section
else:
key_name = KILN_KEY
self._ensure_key_exists(key_name)
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_name, 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(key, option, 0, winreg.REG_SZ, str(value))
def _ensure_key_exists(self, key):
key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, key)
key.Close()
class KilnConfigError(BaseException):
pass
|
Loading...