|
From: Dan G. <dkg...@lb...> - 2008-05-09 12:22:45
|
Hi,
I have a situation where there is some shared information across a
couple of configuration files and I'd like to include one config file in
another (one level of include is fine). I would welcome clever and/or
built-in solutions to this problem. But I thought I would share; below
is my ConfigObj subclass that I use (as a drop-in replacement to
ConfigObj) to solve it. Note that one thing missing from this solution
is proper re-mapping of files and line numbers in error messages.
-Dan
class IncConfigObj(configobj.ConfigObj):
"""Recognize and process '@include <file>' directives
transparently. Do not deal with recursive references, i.e.
ignore @includes inside included files.
"""
def __init__(self, infile, **kw):
"""Take same arguments as ConfigObj, but in the case of a file
object or filename, process @include statements in the file.
"""
if not isinstance(infile, str) and not hasattr(infile, 'read'):
arg = infile # pass to ConfigObj unmodified
# yes, it's a file-like-object or string (filename)
else:
arg = [ ]
if isinstance(infile, file):
f = infile
else:
f = file(infile)
# walk through input file
for line in f:
# look for include directive
if line.strip().startswith('@include'):
# open the include file
inc_path = line.strip().split(None,1)[1]
try:
f = file(inc_path)
except IOError,E:
raise IOError("opening included file "
"'%s': %s" % (inc_path, E))
# include the given file
for inc_line in f:
arg.append(inc_line)
# otherwise just keep going
else:
arg.append(line)
configobj.ConfigObj.__init__(self, arg, **kw)
--
Dan Gunter. voice:510-495-2504 fax:510-486-6363 dsd.lbl.gov/~dang
|