我想在Python中動態地導入配置文件。當我使用__import__和導入之間的Python區別爲
我的代碼工作正常:
import conf.config as config
但是當我使用不能正常工作:
config = __import__("conf.config")
下面是示例程序,結果運行它們時,我得到:
#regularimport.py
import conf.config as config
def read_values(cfg):
for varname in cfg.__dict__.keys():
if varname.startswith('__'):
continue
value = getattr(cfg, varname)
yield (varname, value)
for name,value in read_values(config):
print "Current config: %s = %s" % (name, value)
結果:
$python regularimport.py
Current config: SETTING_TWO = another setting
Current config: SETTING_ONE = some setting
動態導入:
#dynamicimport.py
conf_str = "conf.config"
config = __import__(conf_str)
def read_values(cfg):
for varname in cfg.__dict__.keys():
if varname.startswith('__'):
continue
value = getattr(cfg, varname)
yield (varname, value)
for name,value in read_values(config):
print "Current config: %s = %s" % (name, value)
結果:
$ python dynamicimport.py
Current config: config = <module 'conf.config' from '/home/ubuntu/importex/conf/config.pyc'>
我的問題是,爲什麼不同?更重要的是,如何使動態導入示例像常規導入一樣工作?
第一個問題是,你爲什麼要使用['__import__'(http://docs.python.org/2/library/functions.html#__import__)。你讀過文檔嗎?他們不僅解釋它,而且告訴你如果你不想學習所有可能使用的可怕細節['importlib.import_module'](http://docs.python.org/2改爲/library/importlib.html#importlib.import_module)。 – abarnert