Python 无法捕获线程程序中的异常
下面的Python程序启动一个线程,然后继续在主线程中执行操作。我将整个主线程包装在一个try-except块中,以便在发生异常时可以删除所有正在运行的线程 当我使用Python2.7.5运行脚本并在程序执行期间在随机点调用键盘中断时,会触发异常,但不会捕获异常。程序继续运行Python 无法捕获线程程序中的异常,python,multithreading,unix,exception-handling,python-2.x,Python,Multithreading,Unix,Exception Handling,Python 2.x,下面的Python程序启动一个线程,然后继续在主线程中执行操作。我将整个主线程包装在一个try-except块中,以便在发生异常时可以删除所有正在运行的线程 当我使用Python2.7.5运行脚本并在程序执行期间在随机点调用键盘中断时,会触发异常,但不会捕获异常。程序继续运行 $ python test.py Running server ... Searching for servers ... ^CTraceback (most recent call last): File "tes
$ python test.py
Running server ...
Searching for servers ...
^CTraceback (most recent call last):
File "test.py", line 50, in <module>
main()
File "test.py", line 40, in main
app_main()
File "test.py", line 35, in app_main
searchservers()
File "test.py", line 26, in searchservers
time.sleep(0.0005)
KeyboardInterrupt
为什么键盘中断没有被捕获?捕捉线程程序中的异常并中断整个进程的正确方法是什么?
键盘中断是一种特殊的异常;与MemoryError
、GeneratorExit
和SystemExit
类似,它不是从基异常
类派生的
因此,仅仅捕获异常是不够的;您通常会明确地捕捉到它:
except (Exception, KeyboardInterrupt) as exc:
但是,您还试图捕获线程中的异常;线程有自己的独立堆栈;您不能只是去捕捉在主线程的那些堆栈中抛出的异常。您必须捕获该线程中的异常:
要以通用方式处理此问题并将异常“传递”到主线程,需要某种线程间通信。请参阅完整的解决方案。这是一个非常好的问题,我期待着阅读足够的答案。
except (Exception, KeyboardInterrupt) as exc:
def runserver():
print "Running server ..."
global running
running = True
try:
while running:
time.sleep(0.07)
except (Exception, KeyboardInterrupt) as exc:
print "Error in the runserver thread"