×

注意!页面内容来自https://realpython.com/ref/builtin-exceptions/keyboardinterrupt/,本站不储存任何内容,为了更好的阅读体验进行在线解析,若有广告出现,请及时反馈。若您觉得侵犯了您的利益,请通知我们进行删除,然后访问 原网页

KeyboardInterrupt

In PythonKeyboardInterrupt is a built-in exception that occurs when the user interrupts the execution of a program using the keyboard. This happens when the user presses a key combinationwhich is usually Ctrl+C on most operating systems.

This exception is particularly useful during development and testingas it allows you to terminate long-running or hanging programs gracefully.

KeyboardInterrupt Occurs When

The user presses Ctrl+C during a program’s execution.

KeyboardInterrupt Can Be Used When

  • Stopping a running program during an infinite loop or long computation
  • Interrupting a script that waits for user input or a network response
  • Testing and debugging purposes to halt execution without modifying the code

KeyboardInterrupt Example

An example of when the exception appears:

Python
>>> while True:
...     print("This will run forever unless interrupted")
...
This will run forever unless interrupted
This will run forever unless interrupted
This will run forever unless interrupted
This will run forever unless interrupted
Traceback (most recent call last):
    ...
KeyboardInterrupt

In production codeyou shouldn’t catch this exceptionas doing so could prevent users from stopping the program execution when necessary. Raising KeyboardInterrupt manually is uncommon since it’s specifically for user interrupts.

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorialyou'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finallyyou'll learn how to raise some of these exceptions in your code.

intermediate python

For additional information on related topicstake a look at the following resources:


By Leodanis Pozo Ramos • Updated May 232025