VSCode 如何断点调试 uv:`uv run langchain serve` - 前端学 FastAPI 系列

11 阅读1分钟

How to debug `uv run ...` python program in VSCode

想要调试下 FastAPI 中 sqlmodel(底层是 sqlalchemy)是如何通过主键 id 获取一个数据库记录的:

@app.get("/heroes/{hero_id}")
def read_hero(hero_id: int, session: SessionDep) -> HeroPublic:
    hero = session.get(Hero, hero_id)

    if not hero:
        raise HTTPException(status_code=404, detail="Hero not found")

    return HeroPublic.model_validate(hero)

今天尝试了很久才成功在 uv run langchain serve 运行的 python 程序中打断点。当然 Trae 等 VSCode IDE 一律可用。

👩‍🏫 抄作业

.vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "✅ `uv run langchain serve` debugger",
      "type": "debugpy",
      "request": "launch",
      "program": "${workspaceFolder}/.venv/Scripts/langchain.exe",
      "args": ["serve"],
      "console": "integratedTerminal",
      "justMyCode": false,
      "cwd": "${workspaceFolder}",
      "env": {
        "PYTHONPATH": "${workspaceFolder}"
      }
    }
  ]
}

说明

  1. 因为我们想调试包源码,故 "justMyCode": false
  2. langchain 位置如何确定?首先进入项目根目录且确保虚拟环境已经启动:
which langchain 
/f/workspace/github/my-app/.venv/Scripts/langchain

or

❯ uv run which langchain
/f/workspace/github/my-app/.venv/Scripts/langchain

注意 Windows 需要加 .exe "program": "${workspaceFolder}/.venv/Scripts/langchain.exe", 否则报错:

FileNotFoundError: [Errno 2] No such file or directory: 'F:\workspace\github\my-app\.venv\Scripts\langchain'

🐞 开启调试

已 Trae 为例:打断点 → 然后点击左侧 Bug 小虫子 🐞 标志 → 下拉框选择 uv run langchain serve debugger → 点击右侧绿色小虫子(Start Debugging)或直接 F5F5 开启调试,日志如下:

❯  cd F:\\workspace\\github\\my-app ; /usr/bin/env f:\\workspace\\github\\my-app\\.venv\\Scripts\\python.exe c:\\Users\\liuchuanzong\\.trae-cn\\extensions\\ms-python.debugpy-2025.18.0-win32-x64\\bundled\\libs\\debugpy\\launcher 54274 -- F:\\workspace\\github\\my-app/.venv/Scripts/langchain.exe serve
INFO:     Will watch for changes in these directories: ['F:\\workspace\\github\\my-app']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [18892] using StatReload
INFO:     Started server process [16184]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

触发

❯ curl -s http://localhost:8000/heroes/1 | jq

{
  "name": "legend80s",
  "age": null,
  "id": 1
}

可以看到我们的程序断在了我们刚刚打的断点处。

💭 感想

还是 DeepSeek 帮我解决了问题,Kimi 2 胡说八道,社区方案并不可信,uv 官方这个 issue Running uv scripts in debug mode #8558 一直是 open,还在等着 VSCode 官方解决 🐒🐎 🐌。

更多有用文章请关注「JavaScript与编程艺术」。