在Python中捕获Control-C [英] Capture Control-C in Python

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

问题描述

我想知道是否可以以下列方式在python中捕获Control-C:

I want to know if it's possible to catch a Control-C in python in the following manner:

 if input != contr-c:
    #DO THINGS
 else:
    #quit

我已经阅读了尝试,而不是KeyboardInterrupt ,但它们不适用于我。

I've read up on stuff with try and except KeyboardInterrupt but they're not working for me.

推荐答案

考虑阅读这个页面关于处理异常..应该有帮助。

Consider reading this page about handling exceptions.. It should help.

As @abarnert 已经说过,除了KeyboardInterrupt之外,之后的 sys.exit()

As @abarnert has said, do sys.exit() after except KeyboardInterrupt:.

try:
    # DO THINGS
except KeyboardInterrupt:
    # quit
    sys.exit()

您还可以使用内置的 exit()函数,但是 @eryksun 指出, sys。退出更可靠。

You can also use the built in exit() function, but as @eryksun pointed out, sys.exit is more reliable.

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

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