出错时自动启动 python 调试器 [英] Starting python debugger automatically on error

查看:37
本文介绍了出错时自动启动 python 调试器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题我想了很久,一直没有找到合适的解决方案.如果我运行一个脚本并且遇到了一个 IndexError,python 会打印错误的行、位置和快速描述并退出.是否可以在遇到错误时自动启动pdb?我不反对在文件顶部添加额外的导入语句,也不反对添加几行额外的代码.

This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I am not against having an extra import statement at the top of the file, nor a few extra lines of code.

推荐答案

您可以使用 traceback.print_exc 打印异常回溯.然后使用 sys.exc_info 提取回溯,最后调用 pdb.post_mortem 与回溯

You can use traceback.print_exc to print the exceptions traceback. Then use sys.exc_info to extract the traceback and finally call pdb.post_mortem with that traceback

import pdb, traceback, sys

def bombs():
    a = []
    print a[0]

if __name__ == '__main__':
    try:
        bombs()
    except:
        extype, value, tb = sys.exc_info()
        traceback.print_exc()
        pdb.post_mortem(tb)

如果您想使用 code.interact 启动交互式命令行使用引发异常的框架的局部变量,您可以执行

If you want to start an interactive command line with code.interact using the locals of the frame where the exception originated you can do

import traceback, sys, code

def bombs():
    a = []
    print a[0]

if __name__ == '__main__':
    try:
        bombs()
    except:
        type, value, tb = sys.exc_info()
        traceback.print_exc()
        last_frame = lambda tb=tb: last_frame(tb.tb_next) if tb.tb_next else tb
        frame = last_frame().tb_frame
        ns = dict(frame.f_globals)
        ns.update(frame.f_locals)
        code.interact(local=ns)

这篇关于出错时自动启动 python 调试器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆