【问题标题】:/usr/bin/python3: No module named pytest/usr/bin/python3:没有名为 pytest 的模块
【发布时间】:2020-06-13 00:19:22
【问题描述】:

我使用python3 -m pytest 运行我的测试。这在 python3 指向 python3.6 时有效。我安装了 python3.7,使用以下命令将 python3.7 作为我的默认 python3:

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2
sudo update-alternatives --config python3 

并再次为 python3.7 安装了所有必需的软件包。但现在我不能再运行我的测试了。因为它说:/usr/bin/python3: No module named pytest。我没有使用虚拟环境,问题不在于特定模块,因为它也找不到其他模块。它应该与python路径有关。我不知道在python3版本之间切换后要更改什么,以便在/home/ubuntu/.local/lib/python3.x/site-packages/中轻松找到所需的模块。

我现在切换回 python3.6 并获得 ModuleNotFoundError: No module named 'jsonpath_ng',这在切换到 python3.7 之前可以正常工作。这是python3 -m site的输出:

sys.path = [
    '/home/ubuntu',
    '/usr/lib/python36.zip',
    '/usr/lib/python3.6',
    '/usr/lib/python3.6/lib-dynload',
    '/home/ubuntu/.local/lib/python3.6/site-packages',
    '/usr/local/lib/python3.6/dist-packages',
    '/usr/lib/python3/dist-packages',
]
USER_BASE: '/home/ubuntu/.local' (exists)
USER_SITE: '/home/ubuntu/.local/lib/python3.6/site-packages' (exists)
ENABLE_USER_SITE: True

【问题讨论】:

  • 您可能没有使用正确的 PIP 和正确的 Python 解释器。尝试运行python3 -m pip install pytest --user(如果在系统范围内安装,可以省略--user)。系统的 PIP 可能仍在使用错误的 Python 解释器,这可能会解决您的问题。
  • 我运行了那个命令,它说:Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: pytest in /home/ubuntu/.local/lib/python3.7/site-packages (5.3.5)...
  • 非常有趣。您可以尝试进入解释器并运行import pytest 并同时运行import sys; sys.executable 吗?
  • 我进入python3解释器,运行import pytest并没有显示任何错误,然后运行import sys; sys.executable并显示/usr/bin/python3
  • 老实说,我很困惑,因为似乎一切都已正确安装。你可以从 shell 尝试file /usr/bin/python3 吗?例如,就我而言,它给了我/usr/bin/python3: symbolic link to python3.7。这将确认它使用了正确的解释器。

标签: python python-3.x pytest


【解决方案1】:

感谢@hoefling,我通过运行python3 -m site 发现了问题。当我为 root 用户安装所有东西时,我正在使用我的 jenkins 用户而不是 root 运行测试。所以 USER_SITE 对于 jenkins 用户实际上并不存在。我为 jenkins 用户再次安装了所有东西,现在当我使用 python3 -m 时它可以找到模块。

【讨论】:

  • 很高兴我能帮上忙,虽然最后你确实自己找到了问题,所以不太感谢我:-)
  • 你能解释一下你是如何找出 jenkin 用户和 root 用户的吗?我有同样的问题,无法弄清楚解决方案。谢谢。
猜你喜欢
  • 2021-11-09
  • 2021-01-11
  • 2016-01-06
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 2021-09-27
相关资源
最近更新 更多