VSCode中Python脚本出现ModuleNotFoundError问题求助
模块导入错误:是VSCode扩展还是Ubuntu 23.10系统问题?
错误截图可查看项目结构、linksUploader中的代码及导入语句,运行脚本时出现模块找不到的错误,想知道这是VSCode扩展问题还是Ubuntu 23.10系统问题?
相关代码文件
DataEXtractionScripts/linksUploader.py
try: from Utils.Models import LogEntry, MangaLink from Utils.databaseConnection import getCollection from Utils.loggerSetup import loggerSetup except ModuleNotFoundError as e: from Models import MangaLink def uploadLinksFromUserInput(links: List[MangaLink], collection): pass if __name__ == "__main__": links = [MangaLink(url="https://kunmanga.com/manga/invincible-at-the-start/")]
Utils/Models.py
from pydantic import BaseModel, HttpUrl # USED in linksUploader class MangaLink(BaseModel): url: HttpUrl
错误信息
Traceback (most recent call last): File "xyz/MangaTrackerX/DataEXtractionScripts/linksUploader.py", line 5, in <module> from Utils.Models import LogEntry, MangaLink ModuleNotFoundError: No module named 'Utils' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "xyz/MangaTrackerX/DataEXtractionScripts/linksUploader.py", line 9, in <module> from Models import MangaLink ModuleNotFoundError: No module named 'Models'
项目结构
# MangaTrackerX/ │ ├── DataExtractionScripts/ │ |── linksUploader.py └── __init__.py │ └── Utils/ ├── __init__.py ├── Models.py ├── databaseConnection.py └── loggerSetup.py ├── .env ├── .gitignore ├── LICENSE ├── Readme.MD └── requirements.txt
问题原因及解决办法
这既不是VSCode扩展的问题,也不是Ubuntu系统的问题,纯粹是Python模块导入路径的问题。Python找不到Utils和Models模块,是因为运行脚本时的工作目录不在项目根目录MangaTrackerX下,或者项目根目录没被加入Python的搜索路径。
解决方法:
最稳妥的方式:切换到项目根目录运行
打开终端,cd到MangaTrackerX目录,然后执行:python DataExtractionScripts/linksUploader.py不要直接在
DataExtractionScripts文件夹里运行脚本,否则Python无法识别上级目录的Utils模块。用相对导入+模块方式运行
修改linksUploader.py的导入语句为相对导入:try: from ..Utils.Models import LogEntry, MangaLink from ..Utils.databaseConnection import getCollection from ..Utils.loggerSetup import loggerSetup except ModuleNotFoundError as e: pass然后回到项目根目录,用模块方式运行:
python -m DataExtractionScripts.linksUploader手动添加项目路径到Python搜索列表
在linksUploader.py的最开头加入以下代码,强制把项目根目录加入Python路径:import sys from pathlib import Path # 获取项目根目录的绝对路径 project_root = Path(__file__).parent.parent sys.path.append(str(project_root))这样不管你在哪个目录运行脚本,Python都能找到
Utils模块。
内容的提问来源于stack exchange,提问作者Charan
相关产品推荐
相关产品推荐

