简体   繁体   English

是否有“ try:input()除了KeyboardInterrupt:”之外的解决方法

[英]Is there a workaround for “try: input() except KeyboardInterrupt:”

I've searched this topic to no avail for hours. 我搜索这个主题已经有好几个小时了。

Is it possible to do something along the lines of: 是否可以按照以下方式做一些事情:

try:
    input_var = input('> ')
except KeyboardInterrupt:
    print("This will not work.")

But when I try this and do CTRL-C, it just does nothing. 但是,当我尝试执行CTRL-C时,它什么也没做。

Is there any other way to achieve this? 还有其他方法可以做到这一点吗?

Using Windows 10, Python 3.5.2, and Powershell 使用Windows 10,Python 3.5.2和Powershell

Note: I am not using the input_var for printing, I am doing 3 if/elif/else statements based around it. 注意:我没有使用input_var进行打印,而是基于它进行了3条if / elif / else语句。

It sounds like you would be interested in the signal module. 听起来您会对信号模块感兴趣。

This Answer demonstrates how to use the signal module to capture Ctrl+C, or SIGINT. 该答案演示了如何使用信号模块捕获Ctrl + C或SIGINT。

For your use case, something along the lines of the following would work : 对于您的用例,可以执行以下操作:

#!/usr/local/bin/python3
import signal

def signal_handler(signal, frame):
    raise KeyboardInterrupt('SIGINT received')

signal.signal(signal.SIGINT, signal_handler)
try :
    input_var = input('> ')
except KeyboardInterrupt :
    print("CTRL+C Pressed!")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM