FastAPI调试配置问题:launch.json指定venv失败致依赖缺失
解决VS Code调试FastAPI时的环境与路径问题
调试FastAPI应用时遇到三个核心问题:
- 调试命令尝试进入不存在的
graph-storage/graph-storage目录 - 虚拟环境中已安装pandas,但调试时提示
ModuleNotFoundError: No module named 'pandas' - 指定虚拟环境Python路径时VS Code提示无效
1. 修正.env文件格式
打开.dev.env,将PYTHONPATH的定义修改为无空格格式(原配置中的空格会导致路径解析错误):
PYTHONPATH=/home/alexabades/neocareu-api-recomsyst/graph-storage
2. 修正launch.json配置(两种可选方案)
方案一:通过uvicorn模块启动
更新launch.json为以下内容,解决路径、环境继承和虚拟环境指定问题:
{ "version": "0.2.0", "configurations": [ { "name": "Python: FastAPI", "type": "python", "request": "launch", "module": "uvicorn", "cwd": "${workspaceFolder}/graph-storage", "console": "integratedTerminal", "envFile": "${workspaceFolder}/.dev.env", "env": { "PYTHONPATH": "${workspaceFolder}/graph-storage" }, "args": [ "app.server.app:app", "--reload", "--host", "0.0.0.0", "--port", "8000" ], "jinja": true, "justMyCode": true, "python": "${workspaceFolder}/graph-storage/venv/bin/python" } ] }
关键修正:
- 明确设置
PYTHONPATH,确保主进程和uvicorn重载子进程都能正确搜索模块 - 直接指定虚拟环境Python路径,若VS Code提示无效,可替换为绝对路径(如
"/home/alexabades/neocareu-api-recomsyst/graph-storage/venv/bin/python") - 确保
cwd指向正确的graph-storage目录,避免重复路径错误
方案二:直接运行main.py(更贴近手动启动流程)
若方案一仍有问题,可改为直接运行main.py,规避uvicorn子进程的环境继承问题:
{ "version": "0.2.0", "configurations": [ { "name": "Python: FastAPI (Main)", "type": "python", "request": "launch", "program": "${workspaceFolder}/graph-storage/app/main.py", "cwd": "${workspaceFolder}/graph-storage", "console": "integratedTerminal", "envFile": "${workspaceFolder}/.dev.env", "env": { "PYTHONPATH": "${workspaceFolder}/graph-storage" }, "jinja": true, "justMyCode": true, "python": "${workspaceFolder}/graph-storage/venv/bin/python" } ] }
3. 最终检查步骤
- 确认VS Code左下角状态栏的Python解释器已选中
graph-storage/venv/bin/python - 重启VS Code确保配置生效
- 测试虚拟环境能否正常导入pandas:
/home/alexabades/neocareu-api-recomsyst/graph-storage/venv/bin/python -c "import pandas; print(pandas.__version__)"
内容的提问来源于stack exchange,提问作者Alex Abades Grimes
相关产品推荐
相关产品推荐

