Python ConfigParser如何用'${ }'插值?[关闭]

问题描述 投票:1回答:1

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

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

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

在他的例子中,它打印出 "usrlocalbinpython3

我无法复制他的例子,也无法弄清楚它是如何工作的。我可以从配置中抓取其他值,但当我试图抓取 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} 的值是如何被解释的,以及这个值是怎么来的。如果有人能给我解释一下,或者给我指出正确的方向,我将非常感激。

谢谢!我正在关注youtube的一个细节教程。

python configparser
1个回答
0
投票

就像 @wim 在评论中发布的那样,这个值来自 .ini 文件的另一个部分。你可以通过使用 ${sectionName: optionName} 来访问文件中的其他值。

只有当您将ExtendedInterpolation类传递给......时,这才会有效。ConfigParser.

from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
© www.soinside.com 2019 - 2024. All rights reserved.