【Python】ThreadingでKeyboardInterruptをキャッチできない
Author: 水卜
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)