Python 脚本未因键盘中断而退出

问题描述 投票:0回答:2

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

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中),但是键盘中断不起作用。我遵循了this问题并添加了

except KeyboardInterrupt:
声明。当我按
CTRL+C
时,它会再次截屏。有人可以帮忙吗?

python python-imaging-library keyboardinterrupt imagegrab
2个回答
2
投票

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

你想逃离

while
循环;
while
块内的异常在这里处理:

while True:
    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 :   # catch keyboard interrupts and break from loop
        pass

如果您在键盘中断时退出循环,则会离开

while
循环,并且它不会再次抓取。


1
投票

使用以下代码来解决您的问题:

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)
© www.soinside.com 2019 - 2024. All rights reserved.