【问题标题】:Not able to import Python module无法导入 Python 模块
【发布时间】:2019-05-31 06:07:39
【问题描述】:

我在 falcon 中有一个服务器和一个测试模块,但是在运行测试用例时我无法将服务器模块导入到测试模块中。

这是我的层次结构:

project
   |
    --__init__.py
    --server.py
   |
     /tests
        |
          --__init__.py
          -- apitest.py

这是我的测试代码

"""
Unit test for Ping api resource
"""

from falcon import testing
import pytest
import server

@pytest.fixture(scope='module')
def client():
    return testing.TestClient(server.api)

def test_get_message(client):
    result = client.simulate_get('/api/ping')
    assert result.status_code == 200

但是当我运行它时它显示:

Traceback:
apiTest.py:7: in <module>
    import server
E   ImportError: No module named 'server'

我在这里做错了什么。

【问题讨论】:

    标签: python python-3.x pytest python-module falconframework


    【解决方案1】:

    Python 仅在脚本的当前路径中检查模块,在您的情况下为 /tests。您还需要将/project 添加到您的路径中。以下代码 sn-p 应该可以工作:

    import sys
    sys.path.append("../")
    
    import server
    

    【讨论】:

    • 是的,这不是一个最佳实践,因为如果您想要从其他“深度”导入模块,您将需要每次对每个路径都使用此方法
    • 我有更好的方法来代替 sys.path.append 吗? sys.path.append 工作正常。
    • 相对../路径取自脚本执行的位置,而不是文件的绝对路径。这意味着它会中断,除非执行它的 shell 的 cwd 是 tests/。您可以在类似的问题上查看my answer,以使路径成为绝对路径。
    【解决方案2】:

    首先,您必须将添加项目目录设置为 PYTHONPATH 或将您的项目放入已添加的目录中。这让 python 可以使用你的包。

    您可以在cmd 上使用setcommand 添加目录。例如如果你想添加C:\Python 使用命令set PYTHONPATH = C:\Python

    现在要导入server.py,您必须输入import project.serverfrom project import server

    如果您输入import project.server,要在服务器中使用功能,您必须输入project.server.&lt;fuction&gt;(),如果您使用from project import server,您必须使用server.&lt;function&gt;()

    【讨论】:

      【解决方案3】:

      最好的解决方案是让你的包可以安装,而不是摆弄 PYTHONPATH。在此处查看 python 打包指南:https://packaging.python.org/tutorials/packaging-projects/

      【讨论】:

        猜你喜欢
        • 2013-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-08
        • 2017-11-02
        • 2018-09-17
        • 2017-12-11
        相关资源
        最近更新 更多