Eduardo Fernandes Eduardo Fernandes - 1 year ago 111
Python Question

SafeConfigParser: sections and environment variables

(Using Python 3.4.3)

I want to use environment variables in my config file and I read that I should use

as parameter to achieve it.

mytest = %(HOME)s/.config/my_folder

Since I need to get all the options in a section, I am executing the following code:

userConfig = SafeConfigParser(os.environ)
for section in userConfig.sections():
for item in userConfig.options(section):
print( "### " + section + " -> " + item)

My result is not what I expected. As you can see below, it got not only the option I have in my section (
), but also all the environment variables:

### test -> mytest
### test -> path
### test -> lc_time
### test -> xdg_runtime_dir
### test -> vte_version
### test -> gnome_keyring_control
### test -> user

What am I doing wrong?

I want to be able to parse
but don't want the
adding all my environment variables to each one of its sections.

Answer Source

If I have understood your question and what you want to do correctly, you can avoid the problem by not supplying os.environ as parameter to SafeConfigParser. Instead use it as the vars keyword argument's value when you actually retrieve values using the get() method.

This works because it avoids creating a default section from all your environment variables, but allows their values to be used when referenced for interpolation/expansion purposes.

userConfig = SafeConfigParser()  # DON'T use os.environ here

for section in userConfig.sections():
    for item in userConfig.options(section):
        value = userConfig.get(section, item, vars=os.environ)  # use it here
        print('### [{}] -> {}: {!r}'.format(section, item, value))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download