3

我目前正在调试一个导致异常的 Django 项目。我想进入ipdb事后调试器。我试过ipdb作为脚本调用(参见https://docs.python.org/3/library/pdb.html),但这只是让我进入第一行代码:

> python -m ipdb manage.py runserver
> /Users/kurtpeek/myproject/manage.py(2)<module>()
      1 #!/usr/bin/env python
----> 2 import os
      3 import sys

ipdb> 

如果我按cto continue,我只会遇到错误,不可能在事后检查调试器。大概我可以按n( next) 直到我得到错误,但这会很麻烦。

有没有办法通过python manage.py runserver事后调试运行?

4

1 回答 1

0

如果您知道导致异常的行,但不知道异常在其内部有多“深”,您可以通过捕获异常并调用ipdb.post_mortem()异常处理程序来获取它的事后调试器。

例如,从此更改您的代码:

def index(request):
    output = function_that_causes_some_exception()
    return HttpResponse(output)

对此:

def index(request):
    try:
        output = function_that_causes_some_exception()
    except:
        import ipdb
        ipdb.post_mortem()
        # Let the framework handle the exception as usual:
        raise
    return HttpResponse(output)

顺便说一句,对于可能从其他线程在控制台中喷出东西的服务器框架,我强烈推荐wdb,这样您就可以从浏览器的舒适中调试您的 django 应用程序:

def index(request):
    try:
        output = function_that_causes_some_exception()
    except:
        import wdb
        wdb.post_mortem()
        # Let the framework handle the exception as usual:
        raise
    return HttpResponse(output)
于 2021-12-30T20:31:38.003 回答