Parsing environment variables in ConfigParser files

Skip Montanaro skip at pobox.com
Fri Dec 19 12:57:36 EST 2003


    Matthew> I'm considering submitting a patch for Python 2.4 to allow
    Matthew> environment variable expansion in ConfigParser files.
    
       data_file=${HOME}/mydata.dat -> data_file=/home/matt/mydata.dat

    Matthew> The change is pretty straight-forward, but I'm interested in
    Matthew> feedback on whether this is a good idea, what the syntax for
    Matthew> environment variable references should look like (currently I'm
    Matthew> thinking ${varname}), or whether there are any hidden
    Matthew> complexities or backward-compatibility concerns.

There is already a %(foo)s expansion capability in ConfigParser, though the
source of key/value pairs is different.  I'd check to see if it can be bent
(twisted?) to your needs by subclassing ConfigParser and merging a suitably
munged os.environ with the user's config file.  Using your example, the
DEFAULT info would be synthesized or augmented to look like (logically
speaking, this might simply be modified to parse os.environ before reading
the config file):

    [DEFAULT]
    # stuff imported from os.environ
    HOME=/home/matt
    USER=matt
    ...
    # user's other DEFAULT settings
    ...

and a simple regular expression replace would be performed on the actual
config file roughly like so:

    configf = file("config.ini")
    configdata = re.sub(r'${([^}]+)}', r'%(\1)s', configf.read())
    configf = StringIO.StringIO(configdata)
    configf.seek(0)

Skip





More information about the Python-list mailing list