Last active
November 20, 2023 09:38
-
-
Save malexer/ee2f93b1973120925e8beb3f36b184b8 to your computer and use it in GitHub Desktop.
Python 3: ConfigParser with expanding Environment variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, right, there was a mistake, thanks.
I have fixed it, please check the updated version
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
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 ...