提问人:Daniil Stepanov 提问时间:5/9/2023 更新时间:5/9/2023 访问量:121
Python KeyboardInterrupt 线程时
Python KeyboardInterrupt when threading
问:
我试图了解如何在 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 异常时,但我在控制台中也有回溯。
答: 暂无答案
评论