Python KeyboardInterrupt 线程时

Python KeyboardInterrupt when threading

提问人:Daniil Stepanov 提问时间:5/9/2023 更新时间:5/9/2023 访问量:121

问:

我试图了解如何在 python 中引发异常。 我有以下代码:

import threading
import time


def first_thread():
    print(f'Start first thread')
    time.sleep(2)
    print(f'End first thread')


def second_thread():
    print(f'Start second thread')
    time.sleep(5)
    print(f'End second thread')


if __name__ == '__main__':
    first = threading.Thread(target=first_thread)
    second = threading.Thread(target=second_thread)
    try:
        print(f'Current number of threads: {threading.active_count()}')
        first.start()
        second.start()
        print(f'Current number of threads: {threading.active_count()}')
        first.join()
        second.join()
        print(f'Current number of threads: {threading.active_count()}')
    except KeyboardInterrupt as exc:
        print(f'Get the following exception: {exc}')

此代码的输出:

test_test % python3 test_simple.py
Current number of threads: 1
Start first thread
Start second thread
Current number of threads: 3
^CGet the following exception: 
^CException ignored in: <module 'threading' from '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py'>
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 1307, in _shutdown
    lock.acquire()
KeyboardInterrupt

我的问题是为什么当我尝试提出 KeyboardInterrupt excpetion try except statement catch KeyboardInterrupt 异常时,但我在控制台中也有回溯

Python 多线程 异常 keyboardinterrupt

评论

0赞 Pravash Panigrahi 5/9/2023
这回答了你的问题吗?线程忽略 KeyboardInterrupt 异常
0赞 Daniil Stepanov 5/9/2023
@PravashPanigrahi,我认为这不是我的情况。我抓住了异常,但是要退出脚本,我需要将双“control”+“C”放在终端上,所以我不明白为什么......

答: 暂无答案