VS Code Python调试器无法导入本地模块求助
问题描述
我按以下步骤创建了Python项目结构:
mkdir folder_structuremkdir folder_structure/utilstouch folder_structure/utils/tools.pytouch folder_structure/main.py- 在
main.py中编写代码:
from folder_structure.utils.tools import dummy if __name__ == '__main__': dummy()
- 在
tools.py中编写代码:
def dummy(): print("Dummy")
touch folder_structure/__init__.pytouch folder_structure/utils/__init__.py- 启动VS Code调试器
调试时出现报错:
Exception has occurred: ModuleNotFoundError No module named 'folder_structure' File "/Users/davidmasip/Documents/Others/python-scripts/folder_structure/main.py", line 1, in <module> from folder_structure.utils.tools import dummy
当前launch.json配置:
{ "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal", "env": { "PYTHONPATH": "${workspaceRoot}" } } ] }
使用python -m folder_structure.main命令可以正常运行,但调试时无法导入本地模块,该如何解决?
解决方案
方案1:改用模块模式启动调试
将launch.json中的配置修改为以模块方式启动,和你用python -m运行的逻辑一致:
{ "version": "0.2.0", "configurations": [ { "name": "Python: Module", "type": "python", "request": "launch", "module": "folder_structure.main", "console": "integratedTerminal", "env": { "PYTHONPATH": "${workspaceFolder}" } } ] }
- 重点修改:移除
program字段,新增module字段指定要运行的模块(folder_structure.main) - 同时将
${workspaceRoot}替换为${workspaceFolder},这是VS Code当前推荐使用的工作区路径变量
方案2:修复PYTHONPATH变量(如果仍想直接运行文件)
如果坚持要直接运行main.py文件,确保PYTHONPATH指向正确的父目录(即包含folder_structure的python-scripts文件夹):
- 确认你的VS Code工作区根目录是
/Users/davidmasip/Documents/Others/python-scripts - 将
launch.json中的${workspaceRoot}替换为${workspaceFolder},部分旧版本VS Code中${workspaceRoot}可能存在解析问题 - 若仍不生效,可以直接写死PYTHONPATH的绝对路径:
"env": { "PYTHONPATH": "/Users/davidmasip/Documents/Others/python-scripts" }
方案3:临时代码修复(不推荐长期使用)
在main.py的最顶部添加代码,将项目根目录手动加入Python路径:
import sys from pathlib import Path # 将项目父目录加入PYTHONPATH sys.path.append(str(Path(__file__).parent.parent)) from folder_structure.utils.tools import dummy if __name__ == '__main__': dummy()
这种方式虽然能解决问题,但会让代码和运行环境绑定,不推荐在正式项目中使用。
内容的提问来源于stack exchange,提问作者David Masip
相关产品推荐
相关产品推荐

