python - 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
。有人可以帮忙吗?
解决方案
您需要将键盘中断异常处理上移一个。键盘中断永远不会到达您的外部 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 循环并且不会再次抓取。
推荐阅读
- docker - 在多阶段 docker 文件中重新使用 CLI 安装
- git - Git - 从 url 获取库的版本
- javascript - 获取匹配字符串的最后一次出现的索引?
- r - R编程:删除列名
- c++ - 如何在 dll 中编写函数的主体,但在我的主程序中有原型
- javascript - Express-validator .isEmail 验证器不工作
- algorithm - 计算 R 中配对数据的平均值之间的差异
- python - 如何使用python通过文件中的值分隔json文件
- bash - 为什么使用通配符时 Bash 条件不对称?
- javascript - 在 Firebase 中设置对象的名称