首页 > 解决方案 > 从父目录(Python 3)导入包时面临的问题

问题描述

我有以下项目结构:(注意:这是我原始项目的示例结构。)

proj1/
     __init__.py
    App/
        __init__.py
        Handlers/
                __init__.py
                Sum.py
    Tests/
         __init__.py
         Handlers/
                 __init__.py
                 SumHandler.py
    tests.py

我的tests.py=>

import unittest
import Tests

def suite():
    suite = unittest.TestSuite()
    module = __import__('Tests.Handlers.SumHandler', fromlist=['object'])
    suite.addTest(unittest.TestSuite(map(unittest.TestLoader().loadTestsFromModule, [module])))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    test_suite = suite()
    result = runner.run (test_suite)
    print("---- START OF TEST RESULTS")
    print(result)
    print("---- END OF TEST RESULTS")

我的__init__.py=>

import sys as _sys
class Package(object):
    def __init__(s, local):
        import os.path
        s.cache = {}
        s.local = dict((k, local[k]) for k in local)
        s.root = os.path.realpath(os.path.dirname(s.local["__file__"]))
    def __getattr__(s, k):
        if k in s.local: return s.local[k]
        if k in s.cache: return s.cache[k]
        path = list(s.local["_sys"].path)
        s.local["_sys"].path = [s.root]
        try:
            module = __import__(k, globals(), locals(), ['object'], 0)
            name = k[0].capitalize() + k[1:]
            s.cache[k] = getattr(module, name) if hasattr(module, name) else module
        finally: s.local["_sys"].path[:] = path
        return s.cache[k]
_sys.modules[__name__] = Package(locals())

我的SumHandler.py=>

import unittest
import App

class SumHandler(unittest.TestCase):

    def setUp(self):
        self.a = 10
        self.b = 5
        self.sum = App.Handlers.Sum()

    def test_add(self):
        self.assertEqual(self.sum.add(self.a, self.b),15)

    def tearDown(self):
        del(self.a, self.b)

我的Sum.py=>

class Sum():
    def add(self, x, y):
        return x + y

我正在使用unittest 框架来测试我的 App 目录中的代码。现在,当我tests.py使用上述目录结构运行文件时,出现以下错误 =>

Traceback (most recent call last):
  File "/Users/Sharvin/proj_1/Tests/Handlers/SumHandler.py", line 9, in setUp
    self.sum = App.Handlers.Sum()
AttributeError: module 'App' has no attribute 'Handlers'

问题:

我正在尝试将整个App目录导入SumHandler包中,Tests/Handlers以便我可以从App目录中导入多个包。我怎样才能做到这一点?

标签: pythonpython-3.xpython-importpython-packaging

解决方案


推荐阅读