Python keyboard interrupt handler

Python KeyboardInterrupt

Python KeyboardInterrupt

We already know the exceptions and how to handle them in Python. In layman’s language, exceptions are something that interrupts the normal flow of the program. Similarly, the KeyboardInterrupt exception is a Python exception that is raised when the user or programmer interrupts the normal execution of a program. The interpreter in Python regularly checks for any interrupts while executing the program. In Python, the interpreter throws a KeyboardInterrupt exception when the user/programmer presses the ctrl – c or del key either accidentally or intentionally.

As observed in the example above, the KeyboardInterrupt exception is a standard exception used to handle keyboard-related issues. There is no specific syntax unique to the KeyboardInterrupt exception in Python; it is handled like any other exception using the try-except block within the code. The code that might generate the exception is placed within the try block, and it is either explicitly raised using the ‘raise’ keyword or automatically raised by the Python interpreter. To handle the exception and perform desired actions, specific code is written within the except block.

try: # code that can raise the exception # raising this exception is not mandatory raise KeyboardInterrupt except KeyboardInterrupt: # code to perform any specific tasks to catch that exception

How does KeyboardInterrupt Exception work in Python?

One of the most frustrating aspects of working with Python is that it terminates the program when the user presses Ctrl-C, whether intentionally or accidentally. This can be a significant issue, especially when dealing with tasks such as processing bulk data, retrieving records from a database, or executing large programs that handle multiple tasks simultaneously. This exception works very simply, like other exceptions in Python. The only thing about this exception is that it is user generated, and the computer is not involved in raising it. In order to understand the working of KeyboardInterrupt exception in Python, let’s understand the below-written code first.

try: # code inside the try block which can cause an exception # taking the input ‘name’ from the user name = input('Enter the name of the user ') # writing the different exception class to catch/ handle the exception except EOFError: print('Hello user it is EOF exception, please enter something and run me again') except KeyboardInterrupt: print('Hello user you have pressed ctrl-c button.') # If both the above exception class does not match, else part will get executed else: print('Hello user there is some format error')
  • First, the code inside the try block is executed.
  • If the user presses the ctrl – c, an exception will be raised, and execution of the rest of the statements of the try block is stopped and will move the except block of the raised exception.
  • If no exceptions occur within the try block, the execution continues normally, and no statements within the ‘except’ block are executed.
  • If an exception is raised but does not match the class name specified in the exception handler following the ‘except’ keyword, the program will search for a corresponding catch block outside the inner try block to handle it. If a suitable catch block is not found, the program will exit with a standard Python message.
Читайте также:  Ms excel это редактор html

How to Avoid KeyboardInterrupt Exceptions in Python?

  • There is no such way to avoid the KeyboardInterrupt exception in Python, as it will automatically raise the KeyboardInterrupt exception when the user presses the ctrl – c. There are a few things that we can do in order to avoid this.
  • As we all know, that final block is always executed. So if the exception is raised and we are tangled in some infinite loop, then we can write a clean code in the final block (which will get executed in every case), which can help us to backtrack the situation.
  • It depends on how the programmer he/she codes to avoid this situation, as every programmer has a different way of thinking and hence coding.

Example of Python KeyboardInterrupt

Given below is the example mentioned. General output when the user presses the ctrl – c button.

try: # code inside the try block which can cause an exception # taking the input ‘name’ from the user name = input('Enter the name of the user ') # writing the different exception class to catch/ handle the exception except EOFError: print('Hello user it is EOF exception, please enter something and run me again') except KeyboardInterrupt: print('Hello user you have pressed ctrl-c button.') # If both the above exception class does not match, else part will get executed else: print('Hello user there is some format error')

When the user presses the ctrl -c button on asking the username by the program, the below output is generated.

Python KeyboardInterrupt 1

Explanation:

In the above output, the print statement written for the KeyboardInterrupt exception is displayed as the user presses the ctrl – c, which is a user interrupt exception.

When the user presses the ctrl – d button on asking for the username by the program, the below-given output is generated.

Python KeyboardInterrupt 2

Explanation:

In the provided output, when the user presses the Ctrl-D button, indicating the end of the file, a print statement under the EOF exception class is displayed. This signifies that the specified exception class is checked when the exception occurs.

Conclusion

The above article provides a clear explanation of the KeyboardInterrupt exception in Python. For any programmer, be it a newbie or an expert, it is very important to understand every type of exception in detail to deal with them accordingly and write a program efficiently (able to handle any kind of such situation).

This is a guide to Python KeyboardInterrupt. Here we discuss how KeyboardInterrupt exception works and how to avoid KeyboardInterrupt exceptions in Python with respective examples. You may also have a look at the following articles to learn more –

Источник

Understand KeyboardInterrupt in Python Before You Regret

KeyboardInterrupt

Today seems to be a fine day to learn about KeyboardInterrupt. If you read this article, I can deduce that you have some proficiency with exceptions and exception handling. Don’t sweat it even if you have no knowledge about them; we will give you a brief refresher.

Exceptions are errors that may interrupt the flow of your code and end it prematurely; before even completing its execution. Python has numerous built-in exceptions which inherit from the BaseException class. Check all built-in exceptions from here.

Try-catch blocks handle exceptions, for instance:

try: div_by_zero = 10/0 except Exception as e: print(f"Exception name:") else: print("I would have run if there wasn't any exception") finally: print("I will always run!")

The big idea is to keep that code into a try block which may throw an exception. Except block will catch that exception and do something(statements defined by the user). Finally, block always gets executed, generally used for handling external resources. For instance, database connectivity, closing a file, etc. If there isn’t any exception, code in the else block will also run.

try-catch-finally example

What is Keyboard Interrupt Exception?

KeyboardInterrupt exception is a part of Python’s built-in exceptions. When the programmer presses the ctrl + c or ctrl + z command on their keyboards, when present in a command line(in windows) or in a terminal(in mac os/Linux), this abruptly ends the program amidst execution.

Looping until Keyboard Interrupt

count = 0 whilte True: print(count) count += 1

Try running this code on your machine.

An infinite loop begins, printing and incrementing the value of count. Ctrl + c keyboard shortcut; will interrupt the program. For this reason, program execution comes to a halt. A KeyboardInterrupt message is shown on the screen.

KeyboardInterrupt exception thrown

Python interpreter keeps a watch for any interrupts while executing the program. It throws a KeyboardInterrupt exception whenever it detects the keyboard shortcut Ctrl + c. The programmer might have done this intentionally or unknowingly.

Catching/Handling KeyboardInterrupt

try: while True: print("Program is running") except KeyboardInterrupt: print("Oh! you pressed CTRL + C.") print("Program interrupted.") finally: print("This was an important code, ran at the end.")

Try-except block handles keyboard interrupt exception easily.

Handling keyboard interrupt using try-except-finally

  • In the try block a infinite while loop prints following line- “Program is running”.
  • On pressing ctrl + c, python interpretor detects an keyboard interrupt and halts the program mid execution.
  • After that, finally block finishes its execution.

Catching KeyboardInterrupt using Signal module

Signal handlers of the signal library help perform specific tasks whenever a signal is detected.

import signal import sys import threading def signal_handler(signal, frame): print('\nYou pressed Ctrl+C, keyboardInterrupt detected!') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print('Enter Ctrl+C to initiate keyboard iterrupt:') forever_wait = threading.Event() forever_wait.wait()

Let’s breakdown the code given above:

Catching keyboard interrupt using Signal module

  • SIGINT reperesents signal interrupt. The terminal sends to the process whenever programmer wants to interrupt it.
  • forever_wait event waits forever for a ctrl + c signal from keyboard.
  • signal_handler function on intercepting keyboard interrupt signal will exit the process using sys.exit.

Subprocess KeyboardInterrupt

A subprocess in Python is a task that a python script assigns to the Operative system (OS).

while True: print(f"Program running..")
import sys from subprocess import call try: call([sys.executable, 'process.py'], start_new_session=True) except KeyboardInterrupt: print('[Ctrl C],KeyboardInterrupt exception occured.') else: print('No exception')

Let’s understand the working of the above codes:

Python Subprocess KeyboardInterrupt

  • We have two files, namely, process.py and test.py. In the process.py file, there is an infinite while loop which prints “Program sub_process.py running”.
  • In the try block sys.executeble gives the path to python interpretor to run our subprocess which is process.py.
  • On pressing ctrl + c, python interpretor detects an keyboard interrupt and halts the program mid execution. Later handled by the except block.

FAQs on KeyboardInterrupt

To prevent traceback from popping up, you need to handle the KeyboardInterrupt exception in the except block.
try:
while True:
print(«Running program…»)
except KeyboardInterrupt:
print(«caught keyboard interrupt»)

If a cell block takes too much time to execute, click on the kernel option, then restart the kernel 0,0 option.

When using the flask framework use these functions.
Windows : netstat -ano | findstr
Linux: netstat -nlp | grep
macOS: lsof -P -i :

This is a Python bug. When waiting for a condition in threading.Condition.wait(), KeyboardInterrupt is never sent.
import threading
cond = threading.Condition(threading.Lock()) cond.acquire()
cond.wait(None) print «done»

Conclusion

This article briefly covered topics like exceptions, try-catch blocks, usage of finally, and else. We also learned how keyboard interrupt could abruptly halt the flow of the program. Programmers can use it to exit a never-ending loop or meet a specific condition. We also covered how to handle keyboard interrupt using try-except block in Python. Learned about another way to catch keyboard interrupt exception and interrupted a subprocess.

Источник

Оцените статью