【问题标题】:SafeConfigParser: sections and environment variablesSafeConfigParser:节和环境变量
【发布时间】:2016-09-09 09:19:34
【问题描述】:

(使用 Python 3.4.3)

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

[test]
mytest = %(HOME)s/.config/my_folder

由于我需要获取一个部分中的所有选项,因此我正在执行以下代码:

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

我的结果不是我所期望的。正如您在下面看到的,它不仅获得了我在我的部分 ([test]\mytest) 中的选项,还获得了所有环境变量:

### 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 将我的所有环境变量添加到其每个部分。

【问题讨论】:

    标签: python environment-variables python-3.4 configparser


    【解决方案1】:

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

    这是可行的,因为它避免了从所有环境变量创建 default 部分,但允许在引用它们的值用于插值/扩展时使用它们。

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

    【讨论】:

    • 问题是,如果我在 ini 文件中定义了 %(HOME)s 并且没有将 os.environ 提供给 SafeConfigParser(),sections() 将崩溃,因为它不知道如何处理 HOME。
    • 很奇怪。好的,我会在一个干净的课堂上再试一次,看看你的小费是否能解决问题。谢谢,马蒂诺
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2019-08-21
    • 2016-04-15
    • 1970-01-01
    • 2014-07-03
    • 2012-02-13
    • 2016-04-30
    相关资源
    最近更新 更多