【问题标题】:Python3 'ModuleNotFoundError' when running the code through the terminal, but everything works as intended in a python virtual environment通过终端运行代码时的 Python3 'ModuleNotFoundError',但在 python 虚拟环境中一切正常
【发布时间】:2019-08-12 05:51:17
【问题描述】:

我在使用 Python 导入模块/包时遇到问题。当我在终端(CMD)中运行它时,我注意到了这个问题, 而不是我的 IDE(我使用 PyCharm)。在 PyCharm 中,我使用 Python 3.7 的虚拟环境设置,一切都像魅力一样 并按预期进行。

作为参考,这是在 test_suite.py 中完成导入的方式:

...

from tests.scenarios.test_scenario_01 import TestScenario   # They work perfectly fine
from tests.scenarios.test_scenario_02 import TestScenario2    # written like this in PyCharm venv Python 3.7, but why?

...

这是我的目录的简化版本(没有不必要的文件):

QA System/
├── locators/
│   ├── locators.py
│   ├── __init__.py
├── pages/
│   ├── pages.py
│   └── __init__.py
└── tests/
    ├── reports
    ├── test_scenarios
       ├── test_scenario_01.py
       ├── test_scenario_02.py
       ├── __init__.py
    |── test_suite.py
    |── __init__.py

但是,当通过我的 CMD 手动运行文件 test_suite.py 时(因为我想将它与 Jenkins 集成 最终),我得到这个错误(py -3 test_suite.py):

ModuleNotFoundError: No module named 'tests'

注意:我使用的是最新的 Python 3.7

根据我对 Python 导入的了解,要将目录视为 Python 模块,需要有一个 '__init__.py' 文件 包含在同一目录中。

经过一番研究,我发现可以在 Python 3 中执行不同类型的导入并尝试了它(输入. 在进口名称之前)。像这样:

from .scenarios.test_scenario_01 import TestScenario
from .scenarios.test_scenario_02 import TestScenario2

但是,它仍然没有成功运行,这是我得到的错误:

ModuleNotFoundError: No module named '__main__.scenarios'; '__main__' is not a package

你能帮我解决这个问题吗?

TLDR:导入在 Python3.7 venv 中工作,但不在它之外

【问题讨论】:

  • 你能显示你的 PYTHONPATH 环境变量吗?
  • @Skaperen 我开始认为这可能是问题所在,我根本没有定义 PYTHONPATH 环境变量,它不在我的环境变量列表中。我现在会调查一下。
  • 我做了一些研究,我的 Python 环境变量只有“C:\Python2.7”、“C:\Python2.7\Scripts”、“C:\Users\zheko003\AppData\ Local\Programs\Python\Python37-32" 和 "/Scripts of the same python 37-32 directory.".
  • 可能是因为你没有在 CMD 中激活虚拟环境。找出正在使用的 venv pycharm 并在 CMD 中激活它。

标签: python python-3.x import module virtualenv


【解决方案1】:

我通过在系统环境变量中使用项目路径设置PYTHONPATH 解决了这个问题。作为一个值,我将目录放入项目中。感谢您的提示。

【讨论】:

    【解决方案2】:

    如果是目录 强制使用init.py。在模块中不需要包含 init.py。请检查你的主目录是什么,你的模块是什么。希望这会有所帮助....

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      相关资源
      最近更新 更多