我只使用一个异常处理程序,它将捕获KeyboardInterrupt
并存储异常。然后,在迭代完成的那一刻,如果有一个异常待处理,我将中断循环并重新引发该异常(以使正常的异常处理有机会发生)。
这有效(已在Python 2.7上测试):
x = 1
print "Script started."
stored_exception=None
while True:
try:
print "Processing file #",x,"started...",
# do something time-cosnuming
time.sleep(1)
print " finished."
if stored_exception:
break
x += 1
except KeyboardInterrupt:
stored_exception=sys.exc_info()
print "Bye"
print "x=",x
if stored_exception:
raise stored_exception[0], stored_exception[1], stored_exception[2]
sys.exit()
由于已在评论中发现,此答案对于原始海报不令人满意,这是基于线程的解决方案:
import time
import sys
import threading
print "Script started."
class MyProcessingThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print "Processing file #",x,"started...",
# do something time-cosnuming
time.sleep(1)
print " finished."
for x in range(1,4):
task = MyProcessingThread()
task.start()
try:
task.join()
except KeyboardInterrupt:
break
print "Bye"
print "x=",x
sys.exit()