繁体   English   中英

Python 脚本不退出键盘中断

[英]Python Script not exiting with keyboard Interrupt

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM