Skip to content

Instantly share code, notes, and snippets.

@thoth-ky
Last active February 21, 2020 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thoth-ky/580b7fc4f0b317339e4357bcac74e5ed to your computer and use it in GitHub Desktop.
Save thoth-ky/580b7fc4f0b317339e4357bcac74e5ed to your computer and use it in GitHub Desktop.
This GIST shows how to use configparser to interpolate env variables within
import configparser
import os
class CustomEnvInterpolation(configparser.BasicInterpolation):
"""Interpolation which expands environment variables in values."""
def before_get(self, parser, section, option, value, defaults):
super().before_get(parser, section, option, value, defaults)
if not os.environ.get('MY_ENV'):
os.environ['MY_ENV'] = 'default'
return os.path.expandvars(value)
config = configparser.ConfigParser(interpolation=CustomEnvInterpolation())
def load_config():
config.read('settings.cfg')
load_config()
print(os.environ.get('MY_ENV'))
print(config['settings']['environ'])
[settings]
name = kyalo
environ = ${MY_ENV}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment