Как правильно завершить работу потоков по KeyboardInterrupt?

Хочу по KeyboardInterrupt просто выходить из программы, однако
не понимаю, где обрабатывать это исключение.
from threading import Thread
from time import sleep

def worker(i):
    while True:
        print("worker {}".format(i))
        sleep(i)

threads = [Thread(target=worker, args=(i,)) for i in range(1, 4)]
for t in threads:
    t.start()

for t in threads:
    t.join()
  • Вопрос задан
  • 1112 просмотров
Решения вопроса 1
tumbler
@tumbler Куратор тега Python
бекенд-разработчик на python
https://docs.python.org/3/library/threading.html
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument.

Если обработка KeyboardInterrupt сама по себе не нужна, а хотите чтобы процесс по Ctrl+C завершался - объявите все потоки демонами.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы