SafeConfigParser: sections and environment variables

僤鯓⒐⒋嵵緔 提交于 2019-12-24 01:20:05

问题


(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.


回答1:


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


来源:https://stackoverflow.com/questions/39408101/safeconfigparser-sections-and-environment-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!