Skip to content

Instantly share code, notes, and snippets.

@warabanshi
Last active November 9, 2021 04:38
Show Gist options
  • Save warabanshi/44f6d9ba320d414d3875857f49f1eb1d to your computer and use it in GitHub Desktop.
Save warabanshi/44f6d9ba320d414d3875857f49f1eb1d to your computer and use it in GitHub Desktop.
Extend configparser interpolation to parse environment variables
"""
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