栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

我只使用一个异常处理程序,它将捕获

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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645767.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号