您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在python中按CTRL + C时如何优雅地终止循环

在python中按CTRL + C时如何优雅地终止循环

我只使用一个异常处理程序,它将捕获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()
python 2022/1/1 18:39:55 有353人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶