Lists in ConfigParser

后端 未结 15 1994
清酒与你
清酒与你 2020-11-27 09:38

The typical ConfigParser generated file looks like:

[Section]
bar=foo
[Section 2]
bar2= baz

Now, is there a way to index lists like, for in

15条回答
  •  遥遥无期
    2020-11-27 09:53

    I faced the same problem in the past. If you need more complex lists, consider creating your own parser by inheriting from ConfigParser. Then you would overwrite the get method with that:

        def get(self, section, option):
        """ Get a parameter
        if the returning value is a list, convert string value to a python list"""
        value = SafeConfigParser.get(self, section, option)
        if (value[0] == "[") and (value[-1] == "]"):
            return eval(value)
        else:
            return value
    

    With this solution you will also be able to define dictionaries in your config file.

    But be careful! This is not as safe: this means anyone could run code through your config file. If security is not an issue in your project, I would consider using directly python classes as config files. The following is much more powerful and expendable than a ConfigParser file:

    class Section
        bar = foo
    class Section2
        bar2 = baz
    class Section3
        barList=[ item1, item2 ]
    

提交回复
热议问题