Keyboardinterrupt python ошибка

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

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

Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

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

[Resolved] NameError: Name _mysql is Not Defined

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

  • “Other Commands Don’t Work After on_message” in Discord Bots

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Best Ways to Implement Regex New Line in Python

    Best Ways to Implement Regex New Line in Python

    by Rahul Kumar YadavFebruary 5, 2023

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

Синтаксис обработки исключений

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

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

Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.

Ошибки могут быть разных видов:

  • Синтаксические
  • Недостаточно памяти
  • Ошибки рекурсии
  • Исключения

Разберем их по очереди.

Синтаксические ошибки (SyntaxError)

Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.

Рассмотрим на примере.

a = 8
b = 10
c = a b
File "", line 3
 c = a b
       ^
SyntaxError: invalid syntax

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

Недостаточно памяти (OutofMemoryError)

Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory. Она может появиться по нескольким причинам:

  • Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
  • Загрузка файла большого размера;
  • Запуск модели машинного обучения/глубокого обучения и много другое;

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

Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()), не факт, что все процессы восстановятся — в некоторых случаях MemoryError приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.

Ошибка рекурсии (RecursionError)

Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.

Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.

Чтобы воспроизвести эту ошибку, определим функцию recursion, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.

def recursion():
    return recursion()

recursion()
---------------------------------------------------------------------------

RecursionError                            Traceback (most recent call last)

 in 
----> 1 recursion()


 in recursion()
      1 def recursion():
----> 2     return recursion()


... last 1 frames repeated, from the frame below ...


 in recursion()
      1 def recursion():
----> 2     return recursion()


RecursionError: maximum recursion depth exceeded

Ошибка отступа (IndentationError)

Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.

Пример:

for i in range(10):
    print('Привет Мир!')
  File "", line 2
    print('Привет Мир!')
        ^
IndentationError: expected an indented block

Исключения

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

Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:

Ошибка типа (TypeError)

a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      1 a = 2
      2 b = 'PythonRu'
----> 3 a + b


TypeError: unsupported operand type(s) for +: 'int' and 'str'

Ошибка деления на ноль (ZeroDivisionError)

10 / 0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

 in 
----> 1 10 / 0


ZeroDivisionError: division by zero

Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError и ZeroDivisionError. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.

Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.

Теперь рассмотрим встроенные исключения Python.

Встроенные исключения

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

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

  • Try: он запускает блок кода, в котором ожидается ошибка.
  • Except: здесь определяется тип исключения, который ожидается в блоке try (встроенный или созданный).
  • Else: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).
  • Finally: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.

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

Ошибка прерывания с клавиатуры (KeyboardInterrupt)

Исключение KeyboardInterrupt вызывается при попытке остановить программу с помощью сочетания Ctrl + C или Ctrl + Z в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.

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

try:
    inp = input()
    print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
    print('Исключение KeyboardInterrupt')
else:
    print('Исключений не произошло')

Исключение KeyboardInterrupt

Стандартные ошибки (StandardError)

Рассмотрим некоторые базовые ошибки в программировании.

Арифметические ошибки (ArithmeticError)

  • Ошибка деления на ноль (Zero Division);
  • Ошибка переполнения (OverFlow);
  • Ошибка плавающей точки (Floating Point);

Все перечисленные выше исключения относятся к классу Arithmetic и вызываются при ошибках в арифметических операциях.

Деление на ноль (ZeroDivisionError)

Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.

try:  
    a = 100 / 0
    print(a)
except ZeroDivisionError:  
    print("Исключение ZeroDivisionError." )
else:  
    print("Успех, нет ошибок!")
Исключение ZeroDivisionError.

Переполнение (OverflowError)

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

try:  
    import math
    print(math.exp(1000))
except OverflowError:  
    print("Исключение OverFlow.")
else:  
    print("Успех, нет ошибок!")
Исключение OverFlow.

Ошибка утверждения (AssertionError)

Когда инструкция утверждения не верна, вызывается ошибка утверждения.

Рассмотрим пример. Предположим, есть две переменные: a и b. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert, что приведет к вызову исключения Assertion в том случае, если выражение будет ложным.

try:  
    a = 100
    b = "PythonRu"
    assert a == b
except AssertionError:  
    print("Исключение AssertionError.")
else:  
    print("Успех, нет ошибок!")

Исключение AssertionError.

Ошибка атрибута (AttributeError)

При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes нет атрибута с именем attribute.

class Attributes(obj):
    a = 2
    print(a)

try:
    obj = Attributes()
    print(obj.attribute)
except AttributeError:
    print("Исключение AttributeError.")

2
Исключение AttributeError.

Ошибка импорта (ModuleNotFoundError)

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

import nibabel
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

 in 
----> 1 import nibabel


ModuleNotFoundError: No module named 'nibabel'

Ошибка поиска (LookupError)

LockupError выступает базовым классом для исключений, которые происходят, когда key или index используются для связывания или последовательность списка/словаря неверна или не существует.

Здесь есть два вида исключений:

  • Ошибка индекса (IndexError);
  • Ошибка ключа (KeyError);

Ошибка ключа

Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError.

try:  
    a = {1:'a', 2:'b', 3:'c'}  
    print(a[4])  
except LookupError:  
    print("Исключение KeyError.")
else:  
    print("Успех, нет ошибок!")

Исключение KeyError.

Ошибка индекса

Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).

try:
    a = ['a', 'b', 'c']  
    print(a[4])  
except LookupError:  
    print("Исключение IndexError, индекс списка вне диапазона.")
else:  
    print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.

Ошибка памяти (MemoryError)

Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.

Ошибка имени (NameError)

Ошибка имени возникает, когда локальное или глобальное имя не находится.

В следующем примере переменная ans не определена. Результатом будет ошибка NameError.

try:
    print(ans)
except NameError:  
    print("NameError: переменная 'ans' не определена")
else:  
    print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена

Ошибка выполнения (Runtime Error)

Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.

class BaseClass(object):
    """Опередляем класс"""
    def __init__(self):
        super(BaseClass, self).__init__()
    def do_something(self):
	# функция ничего не делает
        raise NotImplementedError(self.__class__.__name__ + '.do_something')

class SubClass(BaseClass):
    """Реализует функцию"""
    def do_something(self):
        # действительно что-то делает
        print(self.__class__.__name__ + ' что-то делает!')

SubClass().do_something()
BaseClass().do_something()

SubClass что-то делает!



---------------------------------------------------------------------------

NotImplementedError                       Traceback (most recent call last)

 in 
     14
     15 SubClass().do_something()
---> 16 BaseClass().do_something()


 in do_something(self)
      5     def do_something(self):
      6         # функция ничего не делает
----> 7         raise NotImplementedError(self.__class__.__name__ + '.do_something')
      8
      9 class SubClass(BaseClass):


NotImplementedError: BaseClass.do_something

Ошибка типа (TypeError)

Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.

В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.

try:
    a = 5
    b = "PythonRu"
    c = a + b
except TypeError:
    print('Исключение TypeError')
else:
    print('Успех, нет ошибок!')

Исключение TypeError

Ошибка значения (ValueError)

Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.

В этом примере встроенная операция float получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.

try:
    print(float('PythonRu'))
except ValueError:
    print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
    print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'

Пользовательские исключения в Python

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

Это можно сделать, создав новый класс, который будет наследовать из класса Exception в Python.

class UnAcceptedValueError(Exception):   
    def __init__(self, data):    
        self.data = data
    def __str__(self):
        return repr(self.data)

Total_Marks = int(input("Введите общее количество баллов: "))
try:
    Num_of_Sections = int(input("Введите количество разделов: "))
    if(Num_of_Sections < 1):
        raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
    print("Полученная ошибка:", e.data)

Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1

В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.

Недостатки обработки исключений в Python

У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.

Дальше пример, где модуль Python timeit используется для проверки времени исполнения 2 разных инструкций. В stmt1 для обработки ZeroDivisionError используется try-except, а в stmt2if. Затем они выполняются 10000 раз с переменной a=0. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1 с обработкой исключений занимает больше времени чем stmt2, который просто проверяет значение и не делает ничего, если условие не выполнено.

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

import timeit
setup="a=0"
stmt1 = '''
try:
    b=10/a
except ZeroDivisionError:
    pass'''

stmt2 = '''
if a!=0:
    b=10/a'''

print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))

time= 0.003897680000136461
time= 0.0002797570000439009

Выводы!

Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.

Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try выискивает исключения, а except их обрабатывает.

Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.

На чтение 5 мин Просмотров 3к. Опубликовано 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
  1. Use the try...except Statement to Catch the KeyboardInterrupt Error in Python
  2. Use Signal Handlers to Catch the KeyboardInterrupt Error in Python

Catch the KeyboardInterrupt Error in Python

The KeyboardInterrupt error occurs when a user manually tries to halt the running program by using the Ctrl + C or Ctrl + Z commands or by interrupting the kernel in the case of Jupyter Notebook. To prevent the unintended use of KeyboardInterrupt that often occurs, we can use exception handling in Python.

In this guide, you’ll learn how to catch the KeyboardInterrupt error in Python.

Use the try...except Statement to Catch the KeyboardInterrupt Error in Python

The try...except statement is used when it comes to the purpose of exception handling in Python. The try...except statement has a unique syntax; it is divided into three blocks, all of which have a different purpose and function in the Python code.

  • The try block contains the cluster of code that has to be checked for any error by the interpreter.
  • The except block is utilized to add the needed exceptions and bypass the errors of the code.
  • The finally block contains the statements that need to be executed without checking and ignored by the try and except blocks.

To explain the code for KeyboardInterrupt in Python, we take a simple program that asks the user for input while manually handling the KeyboardInterrupt exception.

The following code uses the try...except statement to catch the KeyboardInterrupt error in Python.

try:
    x = input()
    print ('Try using KeyboardInterrupt')
except KeyboardInterrupt:
    print ('KeyboardInterrupt exception is caught')
else:
    print ('No exceptions are caught')

The program above provides the following output.

KeyboardInterrupt exception is caught

In the code above, the input function resides between the try block and is left empty as further details are not needed in this case. Then, the except block handles the KeyboardInterrupt error. The KeyboardInterrupt error is manually raised so that we can identify when the KeyboardInterrupt process occurs.

Python allows the definition of as many except blocks as the user wants in a chunk of code.

Use Signal Handlers to Catch the KeyboardInterrupt Error in Python

The signal module is utilized to provide functions and mechanisms that use signal handlers in Python. We can catch the SIGINT signal, which is basically an interrupt from the keyboard Ctrl+C. Raising the KeyboardInterrupt is the default action when this happens.

The sys module in Python is utilized to provide several necessary variables and functions used to manipulate distinct parts of the Python runtime environment.

The signal and sys modules need to be imported to the Python code to use this method successfully without any error.

The following code uses signal handlers to catch the KeyboardInterrupt error in Python.

import signal
import sys

def sigint_handler(signal, frame):
    print ('KeyboardInterrupt is caught')
    sys.exit(0)
signal.signal(signal.SIGINT, sigint_handler)

The code above provides the following output.

KeyboardInterrupt is caught

In the code above, the signal.signal() function is utilized to define custom handlers to be executed when a signal of a certain type is received.

We should note that a handler, once set for a particular signal, remains installed until the user manually resets it. In this case, the only exception is the handler for SIGCHLD.

Понравилась статья? Поделить с друзьями:
  • Keyboard interface error press f1 to resume как исправить
  • Keyboard interface error please enter setup to recover bios setting
  • Keyboard hook error
  • Keyboard error при включении компьютера что делать
  • Keyboard error windows