问题描述:

Using the code described bellow, i can sucessfully retrieve the properties stored into the file.cfg, but how can i use the output into others variables?

from ConfigParser import SafeConfigParser

class Main:

def get_properties(self, section, *variables):

cfgFile = 'c:\file.cfg'

parser = SafeConfigParser()

parser.read(cfgFile)

properties= variables

return {

variable : parser.get(section,variable) for variable in properties

}

def run_me(self):

config_vars= self.get_properties('database','host','dbname')

print config_vars

op=Main()

op.run_me()

Im still learning Python, but i'm not sure what i need to do to set the output into individual variables:

current output:

{'host': 'localhost', 'dbname': 'sample'}

what i would like to have:

db_host = localhost

db_name = sample

网友答案:
def run_me(self):
     config_vars= self.get_properties('database','host','dbname')
     for key, value in config_vars.items():
         print key, "=", value

You recieved dict-object config_vars, so your can using config variables as values of the dict:

 >>> print config_vars["dbname"]
 sample
 >>> print config_vars["host"]
 localhost

Read more about python dictionaries in documentation.

网友答案:

I would suggest this approach:

import ConfigParser
import inspect

class DBConfig:
    def __init__(self):
        self.host = 'localhost'
        self.dbname = None

    def foo(self): pass

class ConfigProvider:
    def __init__(self, cfg):
        self.cfg = cfg

    def update(self, section, cfg):
        for name, value in inspect.getmembers(cfg):
            if name[0:2] == '__' or inspect.ismethod(value):
                continue

            #print name
            if self.cfg.has_option(section, name):
                setattr(cfg, name, self.cfg.get(section, name))

class Main:
    def __init__(self, dbConfig):
        self.dbConfig = dbConfig

    def run_me(self):
        print('Connecting to %s:%s...' % (self.dbConfig.host, self.dbConfig.dbname))


config = ConfigParser.RawConfigParser()
config.add_section('Demo')
#config.set('Demo', 'host', 'domain.com')
config.set('Demo', 'dbname', 'sample')

configProvider = ConfigProvider(config)

dbConfig = DBConfig()
configProvider.update('Demo', dbConfig)

main = Main(dbConfig)
main.run_me()

The idea is that you collect all important properties in a class (where you can also set the defaults).

The method ConfigProvider.update() will then overwrite those with the values from the config (if they exist).

This allows you to access properties with the simple obj.name syntax.

gist

相关阅读:
Top