使用imp导入模块

时间:2014-02-24 13:10:22

标签: python import

我有一个执行以下操作的脚本:

import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")

稍后,我使用相同的名称调用此模块的类:

config = storage_configuration_reader()

如果我像上面那样导入它,我得到以下NameError NameError: global name 'storage_configuration_reader' is not defined,但如果我使用以下代码:

import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
import storage_configuration_reader
config = storage_configuration_reader()

然后我收到此错误TypeError: 'module' object is not callable

更改imp.load_source的名称无助于导入对象:

import imp
imp.load_source("storage_configuration","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py") 
<module 'storage_configuration' from '/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.pyc'>
 import storage_configuration
 config = storage_configuration_reader()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'storage_configuration_reader' is not defined

导入像这样的对象的最佳方式(AKA工作方式)?

信息:storage_configuration_reader定义:

class storage_configuration_reader(object):
    """ 
    Class configuration_reader: this object read the config file and return the 
    different configuration values
    """
    ...

1 个答案:

答案 0 :(得分:3)

imp.load_source使用给定的path加载模块,并使用新的name命名它,它不像from your_module_at_path import your_class_by_name,它就像import your_module_at_path as new_name(不是完全相同)。

此外,您需要将名称分配给变量以使用它:

wtf=imp.load_source("new_module_name", your_path)
#wtf is the name you could use directly:
config = wtf.storage_configuration_reader()

名称new_module_name作为密钥存储在字典sys.modules中,您可以像这样使用它:

sys.modules['new_module_name'].storage_configuration_reader()
从另一个目录导入模块的

更简单的方法是将模块的路径添加到sys.path

import sys
sys.path.append("/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao")
import storage_configuration_reader
config = storage_configuration_reader.storage_configuration_reader()