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

查看:17
本文介绍了在 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

我已经阅读了有关 try除了 KeyboardInterrupt 的内容,但它们对我不起作用.

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

推荐答案

考虑阅读 this 关于处理异常的页面.. 应该会有所帮助.

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

正如 @abarnert 所说,在 之后执行 sys.exit()除了键盘中断:.

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

类似的东西

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

您也可以使用内置的 exit() 函数,但作为 @eryksun 指出,sys.exit 更可靠.

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天全站免登陆