我从代码生成一个配置文件,假设我能够加载配置文件并使用它。
预期的结果是能够将配置文件中的值分配给变量。
为“LOGS_FORMATTER”键分配内容时,第 22 行的分配失败:
_value = reloaded_config[_section][_key]
这是代码:
import configparser
config = configparser.ConfigParser()
config['APP'] = {
'CERTS_PATH': './certs/',
'DATA_PATH': './data/',
'LOGS_PATH': './logs/',
'LOGS_FORMATTER': '%(message)s',
'LOCAL_ISSUES_FILE_SUFFIX': 'issues.json',
'MAX_RESULTS': '100',
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
reloaded_config = configparser.ConfigParser()
reloaded_config.read('config.ini')
for _section in reloaded_config.sections():
print(f"[{_section}]")
for _key in reloaded_config[_section]:
_value = reloaded_config[_section][_key]
print(f"{_key} = {_value}")
这是输出:
C:\learning\python\configparser>C:/Python312/python.exe c:/learning/python/configparser/failing_configparser.py
[APP]
certs_path = ./certs/
data_path = ./data/
logs_path = ./logs/
Traceback (most recent call last):
File "c:\learning\python\configparser\failing_configparser.py", line 22, in <module>
_value = reloaded_config[_section][_key]
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File "C:\Python312\Lib\configparser.py", line 1223, in __getitem__
return self._parser.get(self._name, key)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\configparser.py", line 777, in get
return self._interpolation.before_get(self, section, option, value,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python312\Lib\configparser.py", line 367, in before_get
self._interpolate_some(parser, option, L, value, section, defaults, 1)
File "C:\Python312\Lib\configparser.py", line 406, in _interpolate_some
raise InterpolationMissingOptionError(
configparser.InterpolationMissingOptionError: Bad value substitution: option 'logs_formatter' in section 'APP' contains an interpolation key 'message' which is not a valid option name. Raw value: '%(message)s'
本次执行的环境:
Microsoft Windows [版本 10.0.22000.2836](又名 Win11)
Python 3.12.0
如果不想进行插值,请指定
interpolation=None
:
reloaded_config = configparser.ConfigParser(interpolation=None)