【问题标题】:Import error from different directory in python (Err - No module named app)从 python 中的不同目录导入错误(错误 - 没有名为 app 的模块)
【发布时间】:2026-01-30 04:45:01
【问题描述】:

我已经看了很多答案,也尝试了其中的大部分,但仍然面临同样的问题

我的结构

 -- backend
    -- app
       -- __init__.py
       -- utils.py
       -- models.py
    -- pytest
       -- test_utils.py`

现在我想将 utils 导入 test_utils 以便能够调用该函数并对其进行测试。我的 init.py 不是空的,我的 test_utils.py 看起来像这样

import sys, os.path
sys.path.insert(0 ,(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + '/app/'))
from utils import test_function

def test_test_function():
  a = test_function(5)
  assert a == 5

我检查了我的 sys 路径也指向正确的目录,但不断收到此错误,我在 Linux 中使用 Python 2.7

ImportError while importing test module '/home/richie/Documents/Project/backend/pytest/test_utils.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../virenv/local/lib/python2.7/site-packages/six.py:709: in exec_
    exec("""exec _code_ in _globs_, _locs_""") 
test_utils.py:3: in <module>
    from utils import test_function
../app/utils.py:15: in <module>
    from models import Users, Accounts
../app/models.py:2: in <module>
    from app import db
E   ImportError: No module named app

【问题讨论】:

  • 您的代码显示from utils import test_function,但错误提示您导入了app。这不是产生该错误的代码。
  • @zvone 我已经添加了完整的错误报告,希望这会有所帮助,但请放心,这是运行的代码,因为我只有 1 个测试文件和 1 个测试用例
  • 尝试将您的pytest 文件夹重命名为另一个名称?它可能与实际的 pytest 模块冲突。
  • 你的 PYTHONPATH 上有后端吗?
  • 这不对。必须列出实际的后端文件夹,才能将子文件夹作为模块拾取。

标签: python python-2.7 python-import pytest importerror


【解决方案1】:

解决方案是在 pytest/ 文件夹中创建一个 pytest.ini 文件。 pytest.ini 的内容是:--

[pytest]

python_paths = . ../应用程序

【讨论】:

    【解决方案2】:

    事实证明,必须将路径添加到应用程序和实用程序,然后才能正常工作

    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
    sys.path.append((os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + '/app/'))
    

    【讨论】:

    • 这是个坏主意。您应该将“app”目录放在路径和import models 上,或者您应该将“app”上方的目录放在路径上然后import app.models。这样做会复制所有模块和类。东西会被导入两次,不容易发现的错误会随着时间的推移而出现。不要那样做。
    最近更新 更多