PyCharm编辑器可识别common包但运行时报ModuleNotFoundError问题
问题原因
PyCharm中配置的Sources源目录仅作用于编辑器自身的语法检查和内置运行环境,PyCharm会自动将这些目录添加到运行时的模块搜索路径sys.path中,因此编辑器无报错。
你直接在终端执行python module1.py时,Python默认只会将当前执行脚本所在的目录(即source/endpoint/user/_get/) 加入模块搜索路径,你配置的source、source/layer目录不在搜索路径范围内,因此抛出模块找不到的错误。
解决方案
下面给出几种常用的解决方式,可根据场景选择:
1. 临时指定PYTHONPATH环境变量(适合临时测试)
运行命令前主动将源目录加入PYTHONPATH,Python运行时会自动读取该环境变量下的路径作为模块搜索路径:
- Linux / Mac 终端执行:
PYTHONPATH=./source:./source/layer python source/endpoint/user/_get/module1.py
- Windows CMD 执行:
set PYTHONPATH=./source;./source/layer && python source/endpoint/user/_get/module1.py
- Windows PowerShell 执行:
$env:PYTHONPATH="./source;./source/layer"; python source/endpoint/user/_get/module1.py
2. 使用-m参数以模块方式运行
不要直接执行py文件,在source目录下执行以下命令,用点分隔模块路径,不需要加.py后缀:
python -m endpoint.user._get.module1
3. 代码内手动添加搜索路径
在module1.py最开头加入代码,主动将源目录加入搜索路径:
import sys from pathlib import Path # 计算得到source目录路径 source_root = Path(__file__).parent.parent.parent.parent # 将source和source/layer加入搜索路径 sys.path.insert(0, str(source_root)) sys.path.insert(0, str(source_root / "layer")) import common
4. 项目打包安装(适合长期维护项目)
给项目添加pyproject.toml或者setup.py打包配置,执行pip install -e .将项目以可编辑模式安装到当前Python环境,之后全局都可以正常导入相关模块,不需要额外配置路径。
内容的提问来源于stack exchange,提问作者psowa001
相关产品推荐
相关产品推荐

