Home > Backend Development > Python Tutorial > How to Gracefully Handle SIGINT Interruptions in Python?

How to Gracefully Handle SIGINT Interruptions in Python?

Patricia Arquette
Release: 2024-12-25 22:36:14
Original
206 people have browsed it

How to Gracefully Handle SIGINT Interruptions in Python?

Handling SIGINT Interruptions in Python Scripts

When working with Python scripts that execute multiple processes and database connections, a graceful exit upon receiving a SIGINT (Ctrl C) interruption is often desirable. In this instance, it becomes necessary to register a handler for SIGINT to perform necessary cleanup tasks.

Python Equivalent of Perl's SIGINT Handling

To achieve the analogue of Perl's SIGINT handling in Python, leverage the signal.signal function as follows:

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

Explanation

  • Register the Handler: The signal.signal(signal.SIGINT, signal_handler) line assigns the signal_handler function as the designated handler for all SIGINT signals.
  • Signal Handler: The signal_handler function is triggered upon receiving SIGINT. Here, it prints a message and gracefully exits the script with sys.exit(0).
  • Print and Pause: After registering the handler, the script prompts the user to press Ctrl C. The signal.pause() call blocks the script until a signal is received.

Additional Resources

  • [signal Module Documentation](https://docs.python.org/3/library/signal.html)

The above is the detailed content of How to Gracefully Handle SIGINT Interruptions 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