A search for how to catch Ctrl-C (SIGINT) in Python often hits the way using the signal
module, but it's a TIPS that makes it easier.
In conclusion, it's okay to catch the KeyboardInterrupt
exception.
Code when using KeyboardInterrupt
:
try:
while True: #Some heavy processing(For or while. .. ..)
pass #Here, Ctrl-Write the process you want to stop with C
except KeyboardInterrupt:
# Ctrl-I caught C!
# print('interrupted!')
pass #If you need any special cleanup, write here
#Sys if you kill the program at this point.exit
#All you have to do is write normal processing, but Ctrl-Note that it is very bad manners to squeeze C and continue processing.
Strictly speaking, KeyboardInterrupt
doesn't seem to catch SIGINT for background jobs that are detached from the shell, but I think it's okay to use KeyboardInterrupt
first in normal situations.
(Reference: https://stackoverflow.com/questions/40775054/capturing-sigint-using-keyboardinterrupt-exception-works-in-terminal-not-in-scr/40785230#40785230)
Recommended Posts