Python 全局异常处理 [英] Python global exception handling

查看:31
本文介绍了Python 全局异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想全局捕获KeyboardInterrupt,并很好地处理它.我不想将整个脚本包含在一个巨大的 try/except 语句中.有没有办法做到这一点?

I want to catch KeyboardInterrupt globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement. Is there any way to do this?

推荐答案

如果你真的不想使用 try/except 你可以改变 sys.excepthook.

You could change sys.excepthook if you really don't want to use a try/except.

import sys
def my_except_hook(exctype, value, traceback):
    if exctype == KeyboardInterrupt:
        print "Handler code goes here"
    else:
        sys.__excepthook__(exctype, value, traceback)
sys.excepthook = my_except_hook

这篇关于Python 全局异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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