Python全局异常处理 [英] Python Global Exception Handling

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

问题描述

所以我想在全球范围内捕获 KeyboardInterrupt ,并且很好地处理它。我不想将我的整个脚本包含在一个巨大的try / except语句中,因为这听起来很大。有没有办法这样做?

So 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, because that just sounds gross. Is there any way to do this?

推荐答案

如果这是在命令行执行的脚本,可以封装你的运行在 main()中的时间逻辑,如果__name__ =='__main __'并将其包装起来,调用它 / p>

If this is a script for execution on the command line, you can encapsulate your run-time logic in main(), call it in an if __name__ == '__main__' and wrap that.

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print 'Killed by user'
        sys.exit(0)

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

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