Sometimes, we want to capture SIGINT in Python.
In this article, we’ll look at how to capture SIGINT in Python.
How to capture SIGINT in Python?
To capture SIGINT in Python, we can use the signal.signal method.
For instance, we write
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()
to call signal.signal with signal.SIGINT and signal_handler to use the signal_handler function to handle the SIGINT event.
In it, we call sys.exit with 0 to exit the script with code 0.
Conclusion
To capture SIGINT in Python, we can use the signal.signal method.