pythonconfigurationini

How to load environment variables in a config.ini file?


I have a config.ini file which contains some properties but I want to read the environment variables inside the config file.

[section1]
 prop1:(from envrinment variable) or value1

Is this possible or do I have to write a method to take care of that?


Solution

  • I know this is late to the party, but someone might find this handy. What you are asking after is value interpolation combined with os.environ.

    Pyramid?

    The logic of doing so is unusual and generally this happens if one has a pyramid server, (which is read by a config file out of the box) while wanting to imitate a django one (which is always set up to read os.environ).
    If you are using pyramid, then pyramid.paster.get_app has the argument options: if you pass os.environ as the dictionary you can use %(variable)s in the ini. Not that this is not specific to pyramid.paster.get_app as the next section shows (but my guess is get_app is the case).

    app.py

    from pyramid.paster import get_app
    from waitress import serve
    import os
    
    app = get_app('production.ini', 'main', options=os.environ)
    serve(app, host='0.0.0.0', port=8000, threads=50)
    

    production.ini:

    [app:main]
    sqlalchemy.url = %(SQL_URL)s
    ...
    

    Configparse?

    The above is using configparser basic interpolation.

    Say I have a file called config.ini with the line

    [System]
    conda_location = %(CONDA_PYTHON_EXE)
    

    The following will work...

    import configparser, os
    cfg = configparser.ConfigParser()
    cfg.read('config.ini')
    print(cfg.get('System', 'conda_location', vars=os.environ))