python - 如何在打开自动重载的情况下在 VSCode 中调试 Django
问题描述
我在 VSCode(Django 应用程序)中设置了调试,它在默认设置下效果很好。但是,在调试时似乎无法自动重新加载。这在 VSCode文档中有说明:
请注意,调试时无法自动重新加载 Django 应用程序。
我想知道是否有某种方法可以使调试(断点等)在 Django 中启用重新加载的情况下工作。
解决方案
事实证明,您可以使用 Microsoft 的debugpy工具来完成这项工作。
Django 在重新加载打开时启动两个进程(默认),其中一个是父进程,另一个是执行重新加载魔法的子进程。
Django 通过在子进程(执行重新加载)中将环境变量设置RUN_MAIN
为 true 来区分这两个进程。参考:https ://github.com/django/django/blob/8a902b7ee622ada258d15fb122092c1f02b82698/django/utils/autoreload.py#L241
通过manage.py
稍微调整,我们可以在父进程中启动一个调试侦听器,并让它在任何重新加载后仍然存在。
添加
debugpy
到但是您管理您的要求(requirements.txt
等)添加以下函数来初始化调试器:
def initialize_debugger():
import debugpy
# optionally check to see what env you're running in, you probably only want this for
# local development, for example: if os.getenv("MY_ENV") == "dev":
# RUN_MAIN envvar is set by the reloader to indicate that this is the
# actual thread running Django. This code is in the parent process and
# initializes the debugger
if not os.getenv("RUN_MAIN"):
debugpy.listen(("0.0.0.0", 9999))
sys.stdout.write("Start the VS Code debugger now, waiting...\n")
debugpy.wait_for_client()
sys.stdout.write("Debugger attached, starting server...\n")
- 修改 manage.py 中的
main
函数如下:
def main()
# <...>
initialize_debugger() # add this
execute_from_command_line(sys.argv)
- 修改 VSCode 中的 launch.json 配置以附加到端口 9999(从上面):
{
"name": "Python: Remote Attach (DebugPy)",
"type": "python",
"request": "attach",
"port": 9999,
"host": "localhost",
},
提示:您可以禁用“未捕获的异常”,因为重新加载本身会导致 SystemExit
推荐阅读
- mysql - 如何从一个表中选择记录,其中第二个表的列中所有记录的值与第一个表的多个列中的任何一个匹配?
- python-3.x - 通过添加 n-1 个目标列,为 n 个目标列重复数据框中的行
- c - 如何将鼠标光标放在c中的程序中?
- javascript - 用python子进程调用javascript
- javascript - “查看更多”按钮无法使用 classlist.add()
- mysql - 当我使用这个查询时
- c# - C# Sendgrid Webhook 请求验证器什么是有效负载?
- angular - Angular RxJS 问题 - 对象的类型为“未知”
- javascript - 在 JavaScript 中创建新的非重复序列?
- slack - 按钮单击时的松弛模态弹出窗口