Home > Backend Development > Python Tutorial > How Can I Gracefully Handle Ctrl C Interrupts (SIGINT) in Python?

How Can I Gracefully Handle Ctrl C Interrupts (SIGINT) in Python?

Linda Hamilton
Release: 2024-12-18 12:00:18
Original
215 people have browsed it

How Can I Gracefully Handle Ctrl C Interrupts (SIGINT) in Python?

Handling SIGINT Signals in Python

In Python, you can respond to SIGINT signals (generated by pressing Ctrl C) by utilizing the signal.signal function. This function registers a handler function that will be executed when the specified signal is received. Here's an example demonstrating how to achieve the same functionality as the provided Perl code:

import signal
import sys

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
Copy after login

In the above code:

  • signal_handler is the registered handler function. When the SIGINT signal is received, this function is called and prints a message to indicate that Ctrl C was pressed. It then exits the script.
  • signal.signal registers the signal_handler function as the handler for SIGINT.
  • print('Press Ctrl C') prints a message to the console asking the user to press Ctrl C.
  • signal.pause() enters the event loop and waits for signals to be delivered. When SIGINT is received, the signal_handler function is executed, and the script exits.

This code provides an effective way to gracefully handle SIGINT signals in Python and perform cleanup actions before exiting the script.

The above is the detailed content of How Can I Gracefully Handle Ctrl C Interrupts (SIGINT) in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template