Python导入问题只能运行应用程序或代码,但不能同时运行两者
所以,我一直在搜索这个网站,并打破了我的头上这个。我的知识似乎将我局限于运行我可以运行的代码或我可以测试的代码。寻找解决方案还没有让我更清楚地理解为什么会这样 我有以下文件夹结构:Python导入问题只能运行应用程序或代码,但不能同时运行两者,python,python-3.x,Python,Python 3.x,所以,我一直在搜索这个网站,并打破了我的头上这个。我的知识似乎将我局限于运行我可以运行的代码或我可以测试的代码。寻找解决方案还没有让我更清楚地理解为什么会这样 我有以下文件夹结构: \uuuu init\uuuu是一个空文件。其余文件如下所示: ClassA.py: class A: def hello(self): print('hello') ClassB.py: from ClassA import A class B: def hello(self)
\uuuu init\uuuu
是一个空文件。其余文件如下所示:
ClassA.py:
class A:
def hello(self):
print('hello')
ClassB.py:
from ClassA import A
class B:
def hello(self):
print('hello')
a = A()
print(a.hello())
main.py:
from ClassB import B
if __name__ == '__main__':
b = B()
b.hello()
test_app.py:
import pytest
import sys
import os
sys.path.append(os.path.realpath(os.path.dirname(__file__)+'/..'))
from src.ClassB import B
def test_app():
assert 1 == 1
如果我从文件的根目录运行项目,一切都会顺利进行。但是,如果我运行测试,它会告诉我:
ModuleNotFoundError: No module named 'ClassA'
我在
ClassB.py
中从ClassA导入A找到了这一问题的原因。它希望我在那里添加一个点,使之成为from.ClassA import a
。但是,如果我添加点,我将无法再运行代码…我认为,通过在tests文件夹中添加\uu init\uuuuuuuuy.py
,您的问题将得到解决。我最终通过将tests文件夹放在src文件夹中来解决它
然而,我“感觉”不对。我还没有找到更好的解决方案。这并不能解决问题。我的问题确实犯了一个错误。我需要加一个。要在代码仅在没有点的情况下运行测试,请执行以下操作。如果您的src和测试文件夹中有init.py文件,您应该能够将
from src.app import*
语句添加到您的测试文件并执行该应用程序