首页 > 解决方案 > Python脚本不退出键盘中断

问题描述

我制作了一个简单的脚本来截取屏幕截图并每隔几秒钟将其保存到一个文件中。这是脚本:

from PIL import ImageGrab as ig
import time
from datetime import datetime

try :
    while (1) :
        tm = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
        try :
            im = ig.grab()
            im.save('/home/user/tmp/' + tm + '.png')
            time.sleep(40)
        except :
            pass
except KeyboardInterrupt:
    print("Process interrupted")
    try :
        exit(0)
    except SystemExit:
        os._exit(0)
        

它工作得很好(在 Ubuntu 18.04,python3 中),但键盘中断不起作用。我关注了这个问题并添加了except KeyboardInterrupt:声明。当我按 时,它再次截取屏幕截图CTRL+C。有人可以帮忙吗?

标签: pythonpython-imaging-librarykeyboardinterruptimagegrab

解决方案


您需要将键盘中断异常处理上移一个。键盘中断永远不会到达您的外部 try/except 块。

您想逃避while循环,while 块内的异常在此处处理:

while True: # had to fix that, sorry :)
    tm = datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
    try :
        im = ig.grab()
        im.save('/home/user/tmp/' + tm + '.png')
        time.sleep(40)
    except :   # need to catch keyboard interrupts here and break from the loop
        pass

如果您在键盘中断时从循环中中断,您将离开 while 循环并且不会再次抓取。


推荐阅读