python - 从父目录(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
目录中导入多个包。我怎样才能做到这一点?
解决方案
推荐阅读
- php - 使用 PHP 在文件夹中上传图像
- java - RecyclerView 没有出现
- go - 从 os.Args [1] 读取时,golang 文件名太长错误
- mongoose - 继续获取 mongoose.Promise 必须是一个函数,得到了 bluebird
- python - 什么模型(损失函数等)可以在 Keras 中用于使用概率标签而不是 one-hot 编码进行分类训练
- node.js - 如何通过我的 IP 地址和路由器端口转发运行 Node 服务器
- html - 如何让我的页脚不阻止 HTML 中的 div 部分?
- javascript - 在 Javascript if 语句中动态生成多个条件
- javascript - React.js 和 [...](扩展)语法
- react-native - 再次运行 componentDidMount 函数 React Native