在程序关闭期间在Python中捕获KeyboardInterrupt [英] Catching KeyboardInterrupt in Python during program shutdown

查看:463
本文介绍了在程序关闭期间在Python中捕获KeyboardInterrupt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写一个命令行实用程序,由于它是生产代码,因此应该能够干净关闭,而不会在屏幕上丢出一堆东西(错误代码,堆栈跟踪等).这意味着我需要捕获键盘中断.

I'm writing a command line utility in Python which, since it is production code, ought to be able to shut down cleanly without dumping a bunch of stuff (error codes, stack traces, etc.) to the screen. This means I need to catch keyboard interrupts.

我已经尝试过同时使用try catch块,例如:

I've tried using both a try catch block like:

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

并捕获信号本身(如发布):

and catching the signal itself (as in this post):

import signal
import sys

def sigint_handler(signal, frame):
    print 'Interrupted'
    sys.exit(0)
signal.signal(signal.SIGINT, sigint_handler)

这两种方法在正常运行期间似乎都能很好地工作.但是,如果在应用程序末尾的清除代码期间发生中断,则Python似乎总是在屏幕上打印一些内容.捕捉到中断会给出

Both methods seem to work quite well during normal operation. However, if the interrupt comes during cleanup code at the end of the application, Python seems to always print something to the screen. Catching the interrupt gives

^CInterrupted
Exception KeyboardInterrupt in <bound method MyClass.__del__ of <path.to.MyClass object at 0x802852b90>> ignored

处理信号既可以

^CInterrupted
Exception SystemExit: 0 in <Finalize object, dead> ignored

^CInterrupted
Exception SystemExit: 0 in <bound method MyClass.__del__ of <path.to.MyClass object at 0x802854a90>> ignored

这些错误不仅丑陋,而且不是很有用(特别是对于没有源代码的最终用户)!

Not only are these errors ugly, they're not very helpful (especially to an end user with no source code)!

此应用程序的清理代码相当大,因此实际用户很有可能会遇到此问题.有什么方法可以捕获或阻止此输出,还是只是我要处理的事情?

The cleanup code for this application is fairly big, so there's a decent chance that this issue will be hit by real users. Is there any way to catch or block this output, or is it just something I'll have to deal with?

推荐答案

结帐该线程,其中包含一些有关退出和回溯的有用信息.

Checkout this thread, it has some useful information about exiting and tracebacks.

如果您只想终止该程序,请尝试执行以下操作(这也会使清理代码中的内容脱颖而出):

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

这篇关于在程序关闭期间在Python中捕获KeyboardInterrupt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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