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 call 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()
We have the signal_handler
function that runs when the SIGINT signal is emitted.
We call signal.signal
with signal.SIGINT
to listen for the SIGINT signal and run signal_handler
when it’s emitted.
Then we call signal.pause
to pause the script and let us watch for the signal.
Now when we press Ctrl+C, we should see 'You pressed Ctrl+C!'
printed.
Conclusion
To capture SIGINT in Python, we can call the signal.signal
method.