Eduardo Fernandes Eduardo Fernandes - 20 days ago 10
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

SafeConfigParser
with
os.environ
as parameter to achieve it.

[test]
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)
userConfig.read(mainConfigFile)
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 (
[test]\mytest
), 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
[test]\mytest
as
/home/myuser/.config/my_folder
but don't want the
SafeConfigParser
adding all my environment variables to each one of its sections.

Answer

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
userConfig.read(mainConfigFile)

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))