You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS Code调试启动配置中进入Hatch Shell调试Django

解决VS Code调试Django时Hatch环境不生效的问题

问题说明

需要先执行hatch shell进入Hatch开发环境,再运行py manage.py runserver启动Django应用,但将hatch shell设为preLaunchTask后,调试器并未在该环境中运行runserver。

原launch.json配置

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Django",
            "type": "debugpy",
            "request": "launch",
            "program": "${workspaceFolder}/testproject/manage.py",
            "args": [
                "runserver"
            ],
            "django": true,
            "justMyCode": true
        }
    ]
}

解决方法

方法1:直接指定Hatch环境的Python解释器

preLaunchTask是独立进程,无法将Hatch环境的变量传递给调试进程,最直接的方式是让调试器直接使用Hatch环境的Python:

  1. 运行hatch env show,找到目标开发环境的Python解释器路径(Windows下通常在.hatch/env/virtual/项目名/default/Scripts/python.exe,Linux/macOS在.hatch/env/virtual/项目名/default/bin/python)。
  2. 修改launch.json,添加python字段指定该路径:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Django (Hatch)",
            "type": "debugpy",
            "request": "launch",
            "python": "${workspaceFolder}/.hatch/env/virtual/testproject/default/Scripts/python.exe", // 替换为你的实际路径
            "program": "${workspaceFolder}/testproject/manage.py",
            "args": [
                "runserver"
            ],
            "django": true,
            "justMyCode": true
        }
    ]
}

方法2:用Hatch命令直接启动调试

通过hatch run命令在环境中启动调试,无需单独进入shell:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Debugger: Django (Hatch)",
            "type": "debugpy",
            "request": "launch",
            "command": "hatch",
            "args": [
                "run",
                "python",
                "${workspaceFolder}/testproject/manage.py",
                "runserver"
            ],
            "django": true,
            "justMyCode": true
        }
    ]
}

注意事项

  • 方法1稳定性更高,推荐优先使用;
  • 确保Hatch环境已正确创建,路径需替换为本地实际路径。

内容的提问来源于stack exchange,提问作者Ledge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 19:12:27