事实证明,您可以使用 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