Aaron
Aaron

Reputation: 475

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.

Is there any other way to achieve this?

Using Windows 10, Python 3.5.2, and Powershell

Note: I am not using the input_var for printing, I am doing 3 if/elif/else statements based around it.

Upvotes: 1

Views: 544

Answers (1)

arbo
arbo

Reputation: 21

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.

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!")

Upvotes: 2

Related Questions