【Python】ThreadingでKeyboardInterruptをキャッチできない
 Author: 水卜

事象

PythonでThreadingを使っていて、ctrl + cで強制終了したとき、except句でKeyboardInterruptを受け取れない。

以下のようなエラーが出るのみ。

Exception ignored in: <module 'threading' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py'>

解決方法

スレッドがis_alive()になった瞬間にjoin()してしまうことで解決した。

while observe_thread.is_alive():
    observe_thread.join()

サンプルコード

以下をコピペして実行し、ctrl + cで終了してみてほしい。

ctrl + cが出力され、拾えているのがわかる。

import threading
import time
alive = True
observe_thread = None

def loop():
    global alive, observe_thread
    try:
        observe_thread = threading.Thread(target=__loop)
        observe_thread.start()
        while observe_thread.is_alive():
            observe_thread.join()
    except KeyboardInterrupt:
        print('ctrl + c')
        alive = False
        pass

def __loop():
    cnt = 0
    while alive:
        print(cnt)
        cnt += 1
        time.sleep(1)