我只使用一个异常处理程序,它将捕获
KeyboardInterrupt并存储异常。然后,在迭代完成的那一刻,如果有一个异常待处理,我将中断循环并重新引发该异常(以使正常的异常处理有机会发生)。
这有效(已在Python 2.7上测试):
x = 1print "script started."stored_exception=Nonewhile 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=",xif stored_exception: raise stored_exception[0], stored_exception[1], stored_exception[2]sys.exit()
编辑: 由于已在评论中发现,此答案对于原始海报不令人满意,这是基于线程的解决方案:
import timeimport sysimport threadingprint "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: breakprint "Bye"print "x=",xsys.exit()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)