[英]ModuleNotFoundError: No module named 'src'. Import modules from another directory without sys.path and execute them from existing directory
Even though it is a common question, I believe I have a weird situation尽管这是一个常见的问题,但我相信我有一个奇怪的情况
MAIN
| --src
| -- data
| -- __init__.py
| -- operation.py
| tests
| __init__.py
| test_file.py
| examples
| __init__.py
| example.py
The contents of test_file.py and example.py are as follows: test_file.py 和 example.py 的内容如下:
from src.data.operation import *
I execute the following command from the powershell by navigating inside the tests folder:我通过在测试文件夹中导航从 powershell 执行以下命令:
python -m pytest -v test_file.py
The test file runs fine without giving any errors.测试文件运行良好,没有出现任何错误。
Now I execute the following command from the powershell by navigating inside the examples folder:现在我通过在示例文件夹中导航从 powershell 执行以下命令:
python -m example.py
This throws me the module error.这给我带来了模块错误。 Even though tests and examples are in the same hierarchy as src, I get the module error only when I execute the example.py file by navigating inside the examples folder.
尽管测试和示例与 src 处于同一层次结构中,但仅当我通过在示例文件夹中导航来执行 example.py 文件时,我才会收到模块错误。 It would be great if someone could explain the logic behind this and what would be the best way to execute example.py in a windows system that does not involve sys.path?
如果有人能解释这背后的逻辑,以及在不涉及 sys.path 的 Windows 系统中执行 example.py 的最佳方法是什么,那就太好了?
It is not possible to import without appending sys.path.不附加 sys.path 就无法导入。 By default, Python looks for its modules and packages in $PYTHONPATH.
默认情况下,Python 在 $PYTHONPATH 中查找其模块和包。 When you import something in the module it 1st searches for a built-in module with that name, it then searches for a file or folder in the list of directories given by the variable sys.path.
当您在模块中导入某些内容时,它首先搜索具有该名称的内置模块,然后在变量 sys.path 给出的目录列表中搜索文件或文件夹。
To successfully import from src, add these lines on top of the example.py要成功从 src 导入,请在 example.py 的顶部添加这些行
import sys
sys.path.insert(0, "PATH_TO_THE_MAIN_FOLDER")
run the module from inside examples folder:从示例文件夹中运行模块:
python -m example
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.