2016-07-05 41 views
0

返回config.read()我有一個config.py讀取多個配置文件。從函數

from ConfigParser import * 

def zones_config(): 
    zones_config = ConfigParser() 
    zones = zones_config.sections() 
    zones_config.read('zones.ini'), zones 

def settings_config(): 
    settings_config = ConfigParser() 
    settings_config.read('settings.ini') 

然後在我的database.py文件:

from utils.config import settings_config 

settings_config() 

#mysqbdb config 
ip = settings_config.get('mysqldb', 'ip') 
username = settings_config.get('mysqldb', 'username') 
password = settings_config.get('mysqldb', 'password') 
database = settings_config.get('mysqldb', 'database') 

不過,我得到以下錯誤:

AttributeError: 'function' object has no attribute 'get' 

回答

5

settings_config是一個函數,而.get()是ConfigParser對象的方法。在database.py

def settings_config_function(): 
    settings_config_object = ConfigParser() 
    settings_config_object.read('settings.ini') 
    return settings_config_object 

然後:這應該更清楚地解釋它

from utils.config import settings_config_function 

config_object = settings_config_function() 

#mysqbdb config 
ip = config_object.get('mysqldb', 'ip') 
username = config_object.get('mysqldb', 'username') 
password = config_object.get('mysqldb', 'password') 
database = config_object.get('mysqldb', 'database') 

編輯:

我還建議你在底部致電

settings_config_object = settings_config_function() 
another_example_config_object = another_example_config_function() 

一次config.py和更高版本只是

from utils.config import settings_config_object, another_example_config_object 

在任何需要配置的文件中,這樣就不必實例化一個新的ConfigParser並讀取每個使用該配置的模塊的配置文件。