Keyboardinterrupt как исправить

Asynchronous exception handling is unfortunately not reliable (exceptions raised by signal handlers, outside contexts via C API, etc). You can increase your chances of handling the async exception properly if there is some coordination in the code about what piece of code is responsible for catching them (highest possible in the call stack seems appropriate except for very critical functions).

The called function (dostuff) or functions further down the stack may itself have a catch for KeyboardInterrupt or BaseException that you didn’t/couldn’t account for.

This trivial case worked just fine with python 2.6.6 (x64) interactive + Windows 7 (64bit):

>>> import time
>>> def foo():
...     try:
...             time.sleep(100)
...     except KeyboardInterrupt:
...             print "INTERRUPTED!"
...
>>> foo()
INTERRUPTED!  #after pressing ctrl+c

EDIT:

Upon further investigation, I tried what I believe is the example that others have used to reproduce the issue. I was lazy so I left out the «finally»

>>> def foo():
...     try:
...             sys.stdin.read()
...     except KeyboardInterrupt:
...             print "BLAH"
...
>>> foo()

This returns immediately after hitting CTRL+C. The interesting thing happened when I immediately tried to call foo again:

>>> foo()

Traceback (most recent call last):
  File "c:Python26libencodingscp437.py", line 14, in decode
    def decode(self,input,errors='strict'):
KeyboardInterrupt

The exception was raised immediately without me hitting CTRL+C.

This would seem to make sense — it appears that we are dealing with nuances in how asynchronous exceptions are handled in Python. It can take several bytecode instructions before the async exception is actually popped and then raised within the current execution context. (That’s the behavior that I’ve seen when playing with it in the past)

See the C API: http://docs.python.org/c-api/init.html#PyThreadState_SetAsyncExc

So this somewhat explains why KeyboardInterrupt gets raised in the context of the execution of the finally statement in this example:

>>> def foo():
...     try:
...             sys.stdin.read()
...     except KeyboardInterrupt:
...             print "interrupt"
...     finally:
...             print "FINALLY"
...
>>> foo()
FINALLY
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in foo
KeyboardInterrupt

There could be some crazy mixing of custom signal handlers mixed with the interpreter’s standard KeyboardInterrupt/CTRL+C handler that’s resulting in this sort of behavior. For example, the read() call sees the signal and bails, but it re-raises the signal after deregistering it’s handler. I wouldn’t know for sure without inspecting the interpreter codebase.

This is why I generally shy away from making use of async exceptions….

EDIT 2

I think there’s a good case for a bug report.

Again more theories…(just based on reading code) See the file object source: http://svn.python.org/view/python/branches/release26-maint/Objects/fileobject.c?revision=81277&view=markup

file_read calls Py_UniversalNewlineFread(). fread can return with an error with errno = EINTR (it performs its own signal handling). In this case Py_UniversalNewlineFread() bails but does not perform any signal checking with PyErr_CheckSignals() so that the handlers can get called synchronously. file_read clears the file error but also does not call PyErr_CheckSignals().

See getline() and getline_via_fgets() for examples of how it’s used. The pattern is documented in this bug report for a similar issue: ( http://bugs.python.org/issue1195 ). So it seems that the signal is handled at an indeterminate time by the interpreter.

I guess there’s little value in diving any deeper since it’s still not clear whether the sys.stdin.read() example is a proper analog of your «dostuff()» function. (there could be multiple bugs at play)

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:{e}")
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

Catching exception

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

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.

  • 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.

Handling keyboard interrupt using try-except-finally

Handling keyboard interrupt using try-except-finally

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:

  • 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.

Catching keyboard interrupt using Signal module

Catching keyboard interrupt using Signal module

[Fixed] modulenotfounderror: no module named ‘_bz2

Subprocess KeyboardInterrupt

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

process.py

while True:
	print(f"Program {__file__} running..")

test.py

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:

  • 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.

Python Subprocess KeyboardInterrupt

Python subprocess KeyboardInterrupt

[Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

FAQs on KeyboardInterrupt 

How to prevent traceback on keyboard interrupt?

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

KeyboardInterrupt in jupyter notebook

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

Flask keyboard interrupt, closing flask application?

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

Interrupt in multiprocessing pool?

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.

Trending Python Articles

  • Efficiently Organize Your Data with Python Trie

    Efficiently Organize Your Data with Python Trie

    May 2, 2023

  • [Fixed] modulenotfounderror: no module named ‘_bz2

    [Fixed] modulenotfounderror: no module named ‘_bz2

    by Namrata GulatiMay 2, 2023

  • [Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

    [Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

    by Namrata GulatiMay 2, 2023

  • Prevent Errors with Python deque Empty Handling

    Prevent Errors with Python deque Empty Handling

    by Namrata GulatiMay 2, 2023

На чтение 5 мин Просмотров 4.5к. Опубликовано 18.03.2022

Поскольку мы очень хорошо знаем, что такое исключения и как ими управлять в Python, мы можем перейти к следующему разделу. С точки зрения непрофессионала, исключения — это все, что нарушает нормальный ход программы. Точно так же KeyboardInterrupt — это исключение Python, которое генерируется, когда пользователь или программист прерывает обычное выполнение программы.

Во время выполнения программы интерпретатор Python регулярно проверяет наличие прерываний. Когда пользователь или программист по ошибке или намеренно нажимает клавишу ctrl-c или del в Python, интерпретатор выдает исключение KeyboardInterrupt.

Исключение KeyboardInterrupt наследует BaseException и, как и другие исключения Python, обрабатывается с помощью оператора try-except, чтобы предотвратить внезапный выход интерпретатора из программы.

Содержание

  1. Исключение KeyboardInterrupt и как оно работает?
  2. Пример 1
  3. Пример 2
  4. Пример 3
  5. Заключение

Исключение KeyboardInterrupt и как оно работает?

KeyboardInterrupt Исключение — это стандартное исключение, которое выдается для управления ошибками клавиатуры. В Python нет специального синтаксиса для исключения KeyboardInterrupt; это обрабатывается в обычном блоке try и exclude. Код, который потенциально вызывает проблему, записывается внутри блока try, а ключевое слово «raise» используется для возбуждения исключения или интерпретатор Python вызывает его автоматически.

Один из самых неприятных аспектов работы с Python заключается в том, что он завершает работу программы, когда пользователь нажимает ctrl-c, намеренно или непреднамеренно, что является серьезной проблемой при работе с большими объемами данных, например при извлечении записей из базы данных. обработка, выполнение большой программы, выполняющей несколько задач одновременно, и так далее.

Это исключение ведет себя так же, как и другие исключения Python. Единственная разница с этим исключением состоит в том, что его создал пользователь и что компьютер не принимал в нем участия. Обратитесь к следующим разделам, чтобы узнать больше об этой концепции.

Пример 1

Когда дело доходит до управления исключениями в Python, используется оператор try…except. Оператор try…except имеет особый синтаксис, разделенный на три части, каждая из которых имеет свое назначение и функцию в коде Python.

Блок try содержит набор кода, который интерпретатор должен проверить на наличие ошибок. Блок exclude добавляет необходимые исключения, чтобы избежать ошибок кода. Последний блок включает в себя предложения, которые должны быть выполнены без проверки, но игнорируются блоками try и exclude.

Мы создадим небольшую программу, которая запрашивает ввод данных от пользователя при ручной обработке исключения KeyboardInterrupt, чтобы продемонстрировать код Python для KeyboardInterrupt. Оператор try…except используется в следующем коде Python для захвата ошибки KeyboardInterrupt.

Мы создадим небольшую программу, которая запрашивает

Результат показан ниже.

Функция ввода расположена между блоками

Функция ввода расположена между блоками try в приведенном выше коде и оставлена ​​пустой, поскольку в этом сценарии дополнительная информация не требуется. Затем блок, если не обрабатывает ошибку KeyboardInterrupt.

Чтобы определить, когда происходит процедура KeyboardInterrupt, мы вручную выдаем ошибку KeyboardInterrupt. Python позволяет пользователю определять столько блоков, если они не хотят, в части кода.

Пример 2

Теперь мы будем использовать обработчики сигналов. В Python модуль signal используется для предложения функций и процессов, использующих обработчики сигналов.

Когда это происходит, KeyboardInterrupt вызывается по умолчанию. Модуль sys в Python предоставляет ряд полезных переменных и функций для управления средой выполнения Python.

Модули signal и sys должны быть включены в код Python, чтобы использовать этот подход без ошибок. Обработчики сигналов используются в следующем коде Python для обнаружения ошибки KeyboardInterrupt.

Модули signal и sys должны быть включены в код Python

Результат приведенного выше кода выглядит следующим образом.

Результат приведенного выше кода вы

Функция signal.signal() используется в приведенном выше коде для указания пользовательских обработчиков, которые будут запускаться при получении сигнала определенного типа. Стоит отметить, что как только обработчик настроен для определенного сигнала, он остается на месте, пока пользователь не сбросит его активно. Обработчик SIGCHLD является единственным исключением в этой ситуации.

Пример 3

Вот последняя программа, которую мы рассмотрим. Код внутри блока try потенциально выдает исключение, а затем принимает введенное пользователем «имя». Затем записываются различные классы исключений для перехвата/обработки исключения. Если классы исключений (как показано в приведенном ниже коде) не совпадают, остальная часть кода будет запущена.

Вот последняя программа, которую мы рассмотрим

Когда пользователь нажимает клавишу ctrl -c, появляется следующий вывод, когда программа запрашивает имя пользователя. Оператор печати, созданный для исключения KeyboardInterrupt, печатается в выходных данных, когда пользователь нажимает ctrl-c, что является исключением пользовательского прерывания.

Когда пользователь нажимает клавишу ctrl -c, появляется следующий вывод

Когда пользователь нажимает клавишу ctrl-d и запрашивает имя пользователя, создается вывод, показанный ниже. Оператор печати, определенный внутри класса исключений EOF, отображается, когда пользователь нажимает кнопку ctrl-d, что означает конец файла. Это указывает, что если в коде обнаружено исключение, выполняется поиск соответствующего класса исключения и выполняется следующий блок.

Когда пользователь нажимает клавишу ctrl-d и запрашивает

Заключение

Исключение KeyboardInterrupt, то, как оно возникает и как оно обрабатывается в Python, описано в предыдущей статье. Исключение KeyboardInterrupt, как следует из его названия, представляет собой простое исключение, которое возникает, когда программа прерывается клавиатурой пользователя. Для любого программиста, новичка или опытного, очень важно понять каждую форму исключения, чтобы правильно с ними справиться и быстро создать программу (способную справиться с любой такой ситуацией).

Python KeyboardInterrupt

Introduction to Python KeyboardInterrupt

As we already know what the exceptions are and how to handle them in Python. In layman language, exceptions are something that interrupts the normal flow of the program. Similarly KeyboardInterrupt is a python exception which is generated when the user/programmer interrupts the normal execution of a program. Interpreter in python checks regularly for any interrupts while executing the program. In python, interpreter throws KeyboardInterrupt exception when the user/programmer presses ctrl – c or del key either accidentally or intentionally. KeyboardInterrupt exception inherits the BaseException and similar to the general exceptions in python, it is handled by try except statement in order to stop abrupt exiting of program by interpreter.

Syntax:

As seen above, KeyboardInterrupt exception is a normal exception which is thrown to handle the keyboard related issues. There is no such specific syntax of KeyboardInterrupt exception in Python, it is handled in the normal try and except block inside the code. Code which can cause the error is placed inside the try block with the ‘raise’ keyword to raise that exception or the python interpreter automatically raises it. To catch the exception and perform desired tasks, special code inside the except block is written.

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 annoying things while working with python is that it exits the program once the user presses ctrl – c either intentionally or mistakenly which is a big problem when the bulk data is getting processed like retrieving records from database, handling, executing a big program handling many tasks at a time, etc. This exception works in a very simple manner like other exceptions in Python. Only thing about this exception is that it is user generated and there is no involvement of the computer in raising it. In order to understand the working of KeyboardInterrupt exception in Python, lets understand the below written code first.

Code:

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')

In the above code:

  • First the code inside the try block is executed.
  • If the user presses the ctrl – c, an exception will be raised, 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 arise in the try block, then the execution continues in a normal manner but no ‘except’ block statements are executed.
  • If the exception is raised but does not match with the class name of the exception handler present after the except keyword, it will start looking for the respective catch block to handle it outside the inner try block. If not found, then it will exit the program with the normal python message.

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 few things that we can do in order to avoid this.
  • As we all know that finally 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 finally block (which will get executed in every case) which can help us to backtrack the situation.
  • It totally depends on the programmer how he/she codes in order to avoid this situation as every programmer has a different way of thinking and hence coding.
  • Some add a flag or variable which gets incremented when the user clicks on the ctrl – c button or some programmers creates a separate function which takes some extra input or keeps track of the user pressing ctrl- c keys and responds accordingly.

Example of Python KeyboardInterrupt

Given below is the example mentioned :

General output when the user presses the ctrl – c button.

Code:

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')

Output 1:

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.

Output 2:

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

Python KeyboardInterrupt 2

Explanation:

In the above output, a print statement written under the EOF exception class is displayed as the user presses the ctrl – d button which indicates the end of file. This indicates that the desired exception class is searched when the exception arises if catched in the code, the following block is executed.

Conclusion

Above article clearly explains what the KeyboardInterrupt exception is, how it is raised and is handled in Python. KeyboardInterrupt exception as the name indicates is a simple exception which is raised when the program is interrupted by the user keyboard. For any programmer be it a newbie or an expert it is very important to understand each and every type of exception in detail in order to deal with them accordingly and write a program efficiently (able to handle any kind of such situations).

Recommended Articles

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

  1. Lambda in Python
  2. Python Iterator Dictionary 
  3. Python BeautifulSoup
  4. Quick Sort in Python

Exceptions are run-time errors that a program encounters during its execution. The “KeyboardInterrupt” exception is one of them which can cause the system to crash. Exception Handling is the process of dealing with such exceptions or events to prevent them. In this tutorial, we will learn How to catch a KeyboardInterrupt in Python using different methods.

If you want to learn more about Python Programming, visit Python Programming Tutorials.

What is a “KeyboardINTERRUPT” EXCEPTION ?

When the user interrupts the program manually by pressing ctrl + c or ctrl + z commands of keyboard, a KeyboardInterrupt exception is raised. Sometimes, the user unintentionally presses the keyboard keys. Interrupting the kernel of jupyter notebook can also raise keyboardinterrupt error which causes the program to halt suddenly in the middle of execution.

Consider an example in which the value of count is incremented on every iteration of an infinite while loop. Press the keyboard shortcut Ctrl + C, you will observe pause that the programme will stop executing. The output screen will display the “KeyboardInterrupt” message.

count = 0
while True:
    print(count)
    count += 1
158861
158862
158863
158864
158865

Process finished with exit code -1073741510 (0xC000013A: interrupted by Ctrl+C)

How to catch a keyboard interrupt?

Exception handling enables programs to continue running without being interrupted. 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.

try:
     raise KeyboardInterrupt
except KeyboardInterrupt:
     print("Keyboard interrupt exception caught")
Keyboard interrupt exception caught

In this article, we have discussed keyboardinterrupt exception in detail and different methods by which you can catch these exceptions. Exception handling is very important to prevent halts and normal running of programs. For any query, contact us. Let us know your feedback about this article.

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти американский флаг
  • Как найти кто украл документы
  • Как найти длину катета если известны углы
  • Как найти трек по видео на телефоне
  • Как исправить ленту в инстаграме

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии