Automatically read configuration values in Python

故事扮演 提交于 2019-12-12 14:57:01

问题


I would like to read a configuration file in Python completely into a data structure without explicitly 'getting' each value. The reason for doing so is that I intend to modify these values programatically (for instance, I'll have a variable that says I want to modify [Foo] Bar = 1 to be [Foo] Bar = 2), with the intention of writing a new configuration file based on my changes.

At present, I'm reading all the values by hand:

parser = SafeConfigParser()
parser.read(cfgFile)
foo_bar1 = int(parser.get('Foo', 'Bar1'))
foo_bar2 = int(parser.get('Foo', 'Bar2'))

What I would love to have (didn't find much Google-wise) is a method to read them into a list, have them be identified easily so that I can pull that value out of the list and change it.

Essentially referencing it as (or similarly to):

config_values = parser.read(cfgFile)
foo_bar1      = config_values('Foo.bar1')

回答1:


import sys
from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.readfp(sys.stdin)

config = dict((section, dict((option, parser.get(section, option))
                             for option in parser.options(section)))
              for section in parser.sections())
print config

Input

[a]
b = 1
c = 2
[d]
e = 3

Output

{'a': {'c': '2', 'b': '1'}, 'd': {'e': '3'}}



回答2:


Sorry if I'm misunderstanding -- This really doesn't seem much different than what you have -- It seems like a very simple subclass would work:

class MyParser(SafeConfigParser):
    def __call__(self,path,type=int):
        return type(self.get(*path.split('.')))

and of course, you wouldn't actually need a subclass either. You could just put the stuff in __call__ into a separate function ...




回答3:


Are you running python 2.7?

There's a nifty way, I discovered a few months back, to parse the config file and setup a dictionary using dictionary comprehension.

config = ConfigParser.ConfigParser()
config.read('config.cfg')
# Create a dictionary of complete config file, {'section':{'option':'values'}, ...}
configDict = {section:{option:config.get(section,option) for option in config.options(section)} for section in config.sections()}

Although this way is harder to read, it take's up less space, and you don't have to explicitly state every variable that you want to get.

  • Note: This won't work on python 2.6 (*that I know of). I've written scripts in the past where I used this, and since I'm running 2.7 on Windows, somebody on a linux machine, running 2.6, will crash on the dictionary comprehension.

--Edit--

You will need to still manually change the data types of the values.



来源:https://stackoverflow.com/questions/13309914/automatically-read-configuration-values-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!