【问题标题】:ExtendedInterpolation() in the Python 2.7 ConfigParserPython 2.7 ConfigParser 中的 ExtendedInterpolation()
【发布时间】:2023-03-14 09:45:01
【问题描述】:

我有 3.x 版本编写的 Python 脚本,由于环境限制,我需要在 2.7 中进行转换。

我设法重构了大部分语法差异和模块导入,但遇到了一行我不知道如何处理的问题:

def readConfigFile(self, file):
        config = ConfigParser.ConfigParser(interpolation = ConfigParser.ExtendedInterpolation())
        config.optionxform = str
        config.read(file)

**config = ConfigParser.ConfigParser(interpolation = ConfigParser.ExtendedInterpolation())**

我在这里找到了一些参考( Python ConfigParser interpolation from foreign section) ,但我不知道如何替换(重构)。

配置解析器:

所以我的问题是,有没有办法重构上面的代码以在 python 2.7 中工作并保留功能?

【问题讨论】:

    标签: python python-2.7 refactoring interpolation


    【解决方案1】:

    正如另一个问题 (Python ConfigParser interpolation from foreign section) 中所述,不,不幸的是,没有简单的方法可以做到这一点。您需要为返回的值创建自己的解析器并对其进行迭代。不过,这似乎有点笨拙。

    【讨论】:

      【解决方案2】:

      我通过使用

      让它在 ArcPy 2.7 中工作
      from backports import configparser
      
      config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
      config.read('path/to/the/config_file.cfg')
      

      然后我在我的配置文件中使用了以下代码:

      [Section 1]
      foo: bar
      

      ...

      [Section 5]
      foo:  ${Section1:foo}
      

      在解释器中尝试调用会产生预测结果:

      config['Section 5']['foo']
      >>> bar
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 2014-02-16
        相关资源
        最近更新 更多