我制作了一个简单的脚本来进行屏幕截图,并每隔几秒钟将其保存到一个文件中。这是脚本:
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循环,不会再抓取。
使用以下代码来解决问题:
from PIL import ImageGrab as ig
import time
from datetime import datetime
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 KeyboardInterrupt: # Breaking here so the program can end
break
except:
pass
print("Process interrupted")
try:
exit(0)
except SystemExit:
os._exit(0)