从ConfigPars中返回可用值

2024-04-25 15:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

使用下面描述的代码,我可以成功地检索存储到文件.cfg,但如何将输出用于其他变量?你知道吗

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()

我还在学习Python,但我不确定要如何将输出设置为单个变量:

电流输出:

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

我想要的是:

db_host = localhost
db_name = sample

Tags: runselfhostparsergetmaindefsection
2条回答

我建议采用这种方法:

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()

其思想是在一个类中收集所有重要的属性(在这个类中还可以设置默认值)。你知道吗

方法ConfigProvider.update()将用配置中的值覆盖这些值(如果它们存在的话)。你知道吗

这允许您使用简单的obj.name语法访问属性。你知道吗

gist

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

您收到了dict对象config_vars,因此可以使用配置变量作为dict的值:

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

阅读documentation中有关python词典的更多信息。你知道吗

相关问题 更多 >