Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 KeyboardInterrupt error

I have noticed that on any python 3 program no matter how basic it is if you press CTRL c it will crash the program for example:

test=input("Say hello")
if test=="hello":
    print("Hello!")
else:
    print("I don't know what to reply I am a basic program without meaning :(")

If you press CTRL c the error will be KeyboardInterrupt is there anyway of stopping this from crashing the program?

The reason I want to do this is because I like to make my programs error proof, and whenever I want to paste something into the input and I accidentally press CTRL c I have to go through my program again..Which is just very annoying.

like image 852
E_J Avatar asked Jun 17 '16 17:06

E_J


People also ask

How does python handle KeyboardInterrupt exception?

In Python, there is no special syntax for the KeyboardInterrupt exception; it is handled in the usual try and except block. The code that potentially causes the problem is written inside the try block, and the 'raise' keyword is used to raise the exception, or the python interpreter raises it automatically.

What is KeyboardInterrupt signal?

In computing, keyboard interrupt may refer to: A special case of signal (computing), a condition (often implemented as an exception) usually generated by the keyboard in the text user interface. A hardware interrupt generated when a key is pressed or released, see keyboard controller (computing)

How do I get an exception on my keyboard?

Keyboard interrupt exceptions can be readily handled with try-except blocks. Place the code that might result in a KeyboardInterrupt exception inside a try block. Use the syntax except error with error as KeyboardInterrupt in the except block to catch the exception.


1 Answers

Control-C will raise a KeyboardInterrupt no matter how much you don't want it to. However, you can pretty easily handle the error, for example, if you wanted to require the user to hit control-c twice in order to quit while getting input you could do something like:

def user_input(prompt):
    try:
        return input(prompt)
    except KeyboardInterrupt:
        print("press control-c again to quit")
    return input(prompt) #let it raise if it happens again

Or to force the user to enter something no matter how many times they use Control-C you could do something like:

def user_input(prompt):
    while True: # broken by return
        try:
            return input(prompt)
        except KeyboardInterrupt:
            print("you are not allowed to quit right now")

Although I would not recommend the second since someone who uses the shortcut would quickly get annoyed at your program.

like image 149
Tadhg McDonald-Jensen Avatar answered Oct 21 '22 00:10

Tadhg McDonald-Jensen