Catch Ctrl-C in Python

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.

Caution

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

Catch Ctrl-C in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
File operations in Python
Read DXF in python
Daily AtCoder # 53 in Python
Key input in Python
Use config.ini in Python
Daily AtCoder # 33 in Python
Solve ABC168D in Python
Logistic distribution in Python
Daily AtCoder # 7 in Python
LU decomposition in Python
One liner in Python
Simple gRPC in Python