I am following a youtube tutorial detailing how to create and read a .ini file with configparser.
In the tutorial, there is a files section like this:
[files]
images_path = /my_app/images
python_path=${settings:packages_path}/bin/python${settings:python_version}
He is reading the data with these lines of code:
from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read('dev.ini')
print(parser.get('files', 'python_path'))
In his example, it prints out '/usr/local/bin/python3'
I am not able to replicate his example or able to figure out how it is working. I am able to grab other values from the config, but get this error when trying to grab 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}'
I am trying to understand how the ${settings.packages_path} value is being interpreted and where the is value coming from. If someone could please explain this or point me in the right direction, I would greatly appreciate it.
Thanks!
As @wim posted in the comments, this value is coming from another section in the .ini file. You can access other values inside the file by using ${sectionName: optionName}.
This will only work if you pass ExtendedInterpolation class to ConfigParser.
from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())