I have an .ini file that point to another ini and want to get a list of these paths

Viewed 23

I have an .ini file that points to another ini and want to get a list of these paths.

for example: file1.ini [Project] Extends=file2.ini

After run this function, I would like to get ['file1.ini', 'file2.ini'] but I get an error:"RecursionError: maximum recursion depth exceeded while calling a Python object" If I understand correctly then the file1.ini is still being reading and I can't understand why.

This is my recursive function:

import configparser
Config = configparser.ConfigParser(strict=False)
Config.optionxform = str


def get_next_ini(ini_file):
    Config.read(ini_file, encoding='latin-1')
    sections = Config.sections()
    if 'Project' in sections:
        options = Config.options("Project")
        if 'Extends' in options:
            new_ini = Config.get('Project', 'Extends')
            return [new_ini] + get_next_ini(new_ini)
    return ""

main:
  get_next_ini('file1.ini'):
1 Answers

I am guessing what is happening is that your final ini file doesn't have a [Project] section. If that is the case then your config parser is simply reopening and reading that last ini file over and over again.

Whether that is the issue or not the likely solution would be to create a unique ConfigParser object for each individual ini file. This way it can't use any values left over from previous parsers. This also eliminates the unnecessary global variable.

For example:

import configparser

def get_next_ini(ini_file):
    Config = configparser.ConfigParser(strict=False)
    Config.read(ini_file, encoding='latin-1')
    sections = Config.sections()
    if 'Project' in sections:
        options = Config.options("Project")
        if 'Extends' in options:
            new_ini = Config.get('Project', 'Extends')
            return [new_ini] + get_next_ini(new_ini)
    return ""

Related