【发布时间】:2010-11-09 17:30:52
【问题描述】:
我想在 Python 中使用 Ctrl+C 停止执行进程。但我在某处读到 KeyboardInterrupt 异常仅在主线程中引发。我还读到在子线程执行时主线程被阻塞。那么如何杀死子线程呢?
例如 Ctrl+C 对以下代码无效:
def main():
try:
thread = threading.Thread(target=f)
thread.start() # thread is totally blocking (e.g. while True)
thread.join()
except KeyboardInterrupt:
print "Ctrl+C pressed..."
sys.exit(1)
def f():
while True:
pass # do the actual work
【问题讨论】:
-
您的主线程没有被阻塞,因为您启动了另一个线程。如果这是真的,线程的意义何在?这是因为您正在调用 thread1.join(),它会阻塞直到 thread1 完成。
标签: python multithreading kill keyboardinterrupt