Skip to content

Instantly share code, notes, and snippets.

@malexer
Last active November 20, 2023 09:38
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save malexer/ee2f93b1973120925e8beb3f36b184b8 to your computer and use it in GitHub Desktop.
Save malexer/ee2f93b1973120925e8beb3f36b184b8 to your computer and use it in GitHub Desktop.
Python 3: ConfigParser with expanding Environment variables
import configparser
import os
class EnvInterpolation(configparser.BasicInterpolation):
"""Interpolation which expands environment variables in values."""
def before_get(self, parser, section, option, value, defaults):
value = super().before_get(parser, section, option, value, defaults)
return os.path.expandvars(value)
cfg = """
[section1]
home_dir: /ITSWORKING
my_dir: %(home_dir)s/YEP
key = value
my_path = $PATH
"""
config = configparser.ConfigParser(interpolation=EnvInterpolation())
config.read_string(cfg)
print(config['section1']['my_path'])
@hbrunie
Copy link

hbrunie commented Jun 3, 2020

with this definition of EnvInterpolation, You can not define an other var like my_newpath = $my_path/new_path.
I think you missed a call to super().before_get(...).
But I couldn't make it work yet ...

@malexer
Copy link
Author

malexer commented Jun 19, 2020

@hbrunie, right, there was a mistake, thanks.
I have fixed it, please check the updated version

@smudge1977
Copy link

Hi Sorry to sound stupid - I was hope that this would use environment variables in preference to config file settings.
Eg. $key = env_value
the config['section']['key'] = env_value
This then means you can make temporary overrides to configuration my setting envs but in a new shell you revert back to the configured settings.
I am sure this is almost what I want but.....

This is what I have changed to achieve this

envvalue = os.environ.get(option) if envvalue == None: return os.path.expandvars(value) else: return envvalue

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment