导入模块 - Python

时间:2015-10-08 21:29:58

标签: python

我的testcases框架上有一堆integration。我在Python中使用importlib库动态加载这些模块。所以,在framework.py里面我有:

def load_class(self, filename, class_str):
    try:
        class_data = filename.split(".")
        current_path = "{0}.{1}".format(self.root, class_data[0])
        module_path = self.format_path(current_path)
        module = importlib.import_module(module_path)
        return getattr(module, class_str)
    except Exception, e:
        log.warning("Failed to instantiate class %s" % class_str)

例如,filename="mock_test.py"class_str="MockTest"。该方法位于framework.py类内,resources内,integration.py位于integration内。像这样:

root / 
     resources /
            __init__.py
            framework.py
     integration /
            __init__.py
            integration.py
            testcases /
                __init__.py
                mock_test.py

所以,从integration我执行该文件,其中包含

import resources.framework as framework
class Integration(framework.Framework):
     def __init__(self, args):
        super(Integration, self).__init__(args)

我收到以下错误:

2015-10-08 14:21:48 - Resources - WARNING - Failed to instantiate class MockTest
2015-10-08 14:21:48 - Resources - ERROR - No module named testcases.mock_test
Traceback (most recent call last):
  File "/root/resources/framework.py", line 92, in load_class
    module = importlib.import_module(module_path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named testcases.mock_test
2015-10-08 14:21:48 - Resources - INFO - Executing TestSuite: sample

我知道发生了什么。但是我不确定解决这个问题的最佳方法,考虑到我想将framework.py用于我设计的其他测试框架。 有人可以帮我解决这个问题吗?

****更新****:

  • 覆盖子类load_class中的方法Integration解决了这个问题。但是代码基本相同。

  • self.root = "integration.testcases"

  • module_path = "integration.testcases.mock_test"
  • class_str="MockTest"

0 个答案:

没有答案