Last active
November 9, 2021 04:38
-
-
Save warabanshi/44f6d9ba320d414d3875857f49f1eb1d to your computer and use it in GitHub Desktop.
Extend configparser interpolation to parse environment variables
This file contains 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
""" | |
This code expects there's a config.ini file under the same directory. | |
And the file is expected like below contents | |
See also below if default values isn't needed | |
https://stackoverflow.com/questions/26586801/configparser-and-string-interpolation-with-env-variable | |
-- config.ini -- | |
[testdayo] | |
envuser=${USERNAME:-defusername} | |
---------------- | |
>> Expected results << | |
$ python EnvInterpolation.py | |
defusername | |
$ USERNAME=envuser python EnvInterpolation.py | |
envuser | |
""" | |
import configparser | |
import os | |
import re | |
class EnvInterpolation(configparser.ExtendedInterpolation): | |
"""Interpolation which expands environment variables in values.""" | |
def before_get(self, parser, section, option, value, defaults): | |
m = re.match(r'\${([A-Z_]+):-(.+)}', value) | |
if m: | |
return os.environ.get(*m.groups()) | |
value = os.path.expandvars(value) | |
return super().before_get(parser, section, option, value, defaults) | |
config = configparser.ConfigParser(interpolation=EnvInterpolation()) | |
config.read('config.ini') | |
print(config['testdayo']['envuser']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment