2012-10-11 32 views
2

使用下面描述的代碼,我可以成功檢索存儲到file.cfg中的屬性,但是如何將輸出用於其他變量?從ConfigParse返回可用值

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 

回答

2
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,所以你可以用配置變量作爲字典值:

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

documentation瞭解更多關於Python字典。

+0

接受您的答案在7分鐘內。感謝您的直接答覆。 –

1

我建議這種做法:

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()將覆蓋那些來自config(如果它們存在)的值。

這使您可以使用簡單的obj.name語法訪問屬性。

gist

+0

感謝您的信息,我會保留此以備將來參考。 –