我希望能够在Python中动态导入一个配置文件。
当使用以下代码时,我的程序可以正常工作:
import conf.config as config
但是当我使用以下代码时,它不能正常工作:
config = __import__("conf.config")
以下是两个示例程序及其运行结果:
示例程序1:
print("Hello, World!")
运行结果:
Hello, World!
示例程序2:
x = 5
y = 7
print(x + y)
运行结果:
12
#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__
。你有看过文档吗?它们不仅解释了它,而且在顶部告诉你,如果你不想学习所有可怕的细节,你应该使用importlib.import_module
。 - abarnert