What's the proper way to retrieve and use the contents of configparser keys and values

20 Views Asked by At

I'm generating a config file from code on the assumption that I'll be able to load the config file and use it.

The expected result is to be able to assign the values in the config file to a variable.

The assignment on line 22 fails when assigning the contents for 'LOGS_FORMATTER' key:

_value = reloaded_config[_section][_key]

Here is the code:

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}")

Here's the output:

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'

The environment of this execution:

Microsoft Windows [Version 10.0.22000.2836] (aka Win11)

Python 3.12.0

1

There are 1 best solutions below

0
user2357112 On

If you don't want to perform interpolation, specify interpolation=None:

reloaded_config = configparser.ConfigParser(interpolation=None)