【问题标题】:Extended interpolation not working in configparser扩展插值在 configparser 中不起作用
【发布时间】:2017-03-16 16:37:42
【问题描述】:

我尝试在 python 3.6 或 python 3.5.1 中使用标准库中的 configparser 模块

我的 ini 文件如下所示:

[common]
domain = http://some_domain_name:8888
about = about/
loginPath = /accounts/login/?next=/home
fileBrowserLink = /filebrowser
partNewDirName = some_dir

[HUE_310]
partNewFilePath = ${common:domain}

我的“主”程序如下所示:

from configparser import ConfigParser

parser = ConfigParser()
parser.read('configfile.ini')

lll = parser.get('HUE_310', 'partNewFilePath')
print(lll)

而不是http://some_domain_name:8888 我得到了${common:domain}

我使用 Pycharm Community 作为我的 IDE。我使用 virtualenv。

我不知道我的代码有什么问题...

【问题讨论】:

    标签: python python-3.x configparser


    【解决方案1】:

    如果你想要扩展插值,你必须创建一个 configparser.ExtendedInterpolation 类的实例,通过调用它,然后使用 interpolation= 关键字创建ConfigParser 实例时的参数如下所示:

    from configparser import ConfigParser, ExtendedInterpolation
    
    parser = ConfigParser(interpolation=ExtendedInterpolation())
    parser.read('configfile.ini')
    
    lll = parser.get('HUE_310', 'partNewFilePath')
    print(lll)  # -> http://some_domain_name:8888
    

    【讨论】:

    • 成功了。谢谢。当我使用它时,我失去了基本的插值,所以为了获得基本和扩展的插值,我使用了类似 basic = ConfigParser(interpolation=BasicInterpolation()) basic.read('config.ini') 的东西。有没有更好的方法来实现这一点?
    • 另外请注意,如果 domainabout 在同一部分中,您可以使用扩展语法在同一部分中执行引用操作,例如 testowy = ${domain}s/${about}s — 所以它可以做“基本”的事情,也是。
    • 不确定你是否理解我最后的评论。通过将%[ 更改为${ExtendedInterpolation 类可以根据引用名称中是否有: 进行 扩展和基本插值。
    • 感谢您指出这一点。现在我明白了。我不需要我的肮脏黑客:)
    • 天哪,这是您在制作对象时必须设置的选项。我在挠头,为什么它不起作用。你为什么不把它放在文档的专用部分下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 2020-11-15
    • 2016-09-29
    • 2019-11-19
    • 1970-01-01
    相关资源
    最近更新 更多