Python ConfigParser 如何使用 '${ }' 插入值?

How does Python ConfigParser Interpolate values with '${ }'?

我正在关注详细介绍如何使用 configparser 创建和读取 .ini 文件的 youtube 教程。

在教程中,有一个这样的文件部分:

[files]
images_path = /my_app/images
python_path=${settings:packages_path}/bin/python${settings:python_version}

他正在使用这些代码行读取数据:

from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read('dev.ini')
print(parser.get('files', 'python_path'))

在他的例子中,它打印出'/usr/local/bin/python3'

我无法复制他的示例或无法弄清楚它是如何工作的。我能够从配置中获取其他值,但是在尝试获取 python_path.

时出现此错误
Traceback (most recent call last):
  File "c:/Users/jeffg/Desktop/ProgrammingProjects/ticket_tracking_system/objects/config_file_read.py", line 12, in <module>
    print(x.getPythonPath())
  File "c:/Users/jeffg/Desktop/ProgrammingProjects/ticket_tracking_system/objects/config_file_read.py", line 8, in getPythonPath
    return self.parser.get('files', 'python_path')
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 799, in get
    return self._interpolation.before_get(self, section, option, value,
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 456, in before_get
    self._interpolate_some(parser, option, L, value, section, defaults, 1)
  File "C:\Users\jeffg\AppData\Local\Programs\Python\Python38-32\lib\configparser.py", line 507, in _interpolate_some
    raise InterpolationMissingOptionError(
configparser.InterpolationMissingOptionError: Bad value substitution: option 'python_path' in section 'files' contains an interpolation key 'settings:packages_path' which is not a valid option name. Raw value: '${settings:packages_path}/bin/python${settings:python_version}'

我正在尝试了解如何解释 ${settings.packages_path} 值以及该值的来源。如果有人可以解释一下或指出正确的方向,我将不胜感激。

谢谢!

正如@wim 在评论中发布的那样,此值来自 .ini 文件中的另一部分。您可以使用 ${sectionName: optionName} 访问文件中的其他值。

这只有在将 ExtendedInterpolation class 传递给 ConfigParser 时才有效。

from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())