Python 当不在工作目录中时出现 ModuleNotFoundError; getcwd 查找模块

Python ModuleNotFoundError when not in working directory; getcwd finds module

当我尝试 运行 带有 python3.6 src/main.py 的 python 文件时(工作目录在 src 之上)从路径导入另一个模块时出现此错误 src:

from src import another_module

ModuleNotFoundError: No module named 'src'

当我做

print(os.getcwd())
print(os.listdir(os.getcwd()))

我得到了预期的结果:

path/to/working/directory

['src']

当我 运行 带有 PyCharm 的脚本时导入有效,但我需要 运行 它在 PyCharm 之外 PyCharm。

当您 运行 在命令行上执行 python 脚本时,脚本的目录(可能与您的 shell 当前工作目录不同) 添加到路径中。

因此,由于 src/ 已经在您的路径中,您可以只说 import another_module

要制作 src 包,制作一个名为 src/__init__.py

的空文件

解决了,方法是在工作目录中创建另一个文件 run.py,从命令中调用 src/main.py 和 运行 run.py行而不是 src/main.py.

在 launch.json 中,将以下行添加到您的部署中:

"env": {"PYTHONPATH": "${workspaceRoot}"}

这似乎迫使 Python 评估相对于 ${workingSpaceRoot} 文件夹的导入;允许您使用完全限定名称:from src import ...

默认行为是相对评估命名空间。因此,您的原始陈述:from src import ... 实际上是在 src/src/....

中查找

(感谢@g4th 在另一个 Whosebug page 上发布了此解决方案。)