本文介绍了SafeConfigParser:部分和环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(使用Python 3.4.3 )

我想在配置文件中使用环境变量,并且我读到应该使用SafeConfigParseros.environ作为参数来实现它.

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)

我的结果与预期不符.如下所示,它不仅有我在本节([test]\mytest)中拥有的选项,还包括所有环境变量:

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

我在做什么错了?

我希望能够将[test]\mytest解析为/home/myuser/.config/my_folder,但又不想SafeConfigParser将我所有的环境变量添加到其每个部分中.

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.

推荐答案

如果我了解您的问题以及您想正确执行的操作,则可以通过 not 来避免此问题. strong>将os.environ作为参数提供给SafeConfigParser.当您实际使用get()方法检索值时,请使用它作为vars关键字参数的值.

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.

之所以行之有效,是因为它避免了从所有环境变量中创建 default 部分,但允许在为插值/扩展目的引用它们时使用它们的值.

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

这篇关于SafeConfigParser:部分和环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:26