简体   繁体   English

Python 脚本不退出键盘中断

[英]Python Script not exiting with keyboard Interrupt

I made a simple script to take screenshots and save it to a file every few seconds.我制作了一个简单的脚本来每隔几秒钟截取屏幕截图并将其保存到文件中。 Here is the script:这是脚本:

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)
        

It works perfectly (in Ubuntu 18.04, python3), but the keyboard interrupt does not work.它完美运行(在 Ubuntu 18.04,python3),但键盘中断不起作用。 I followed this question and added the except KeyboardInterrupt: statement.我按照这个问题添加了except KeyboardInterrupt:声明。 It again takes a screenshot when I press CTRL+C .当我按CTRL+C时,它会再次截图。 Can someone help with this?有人可以帮忙吗?

You need to move your keyboard interrupt exception handling one up.您需要将键盘中断异常处理上移。 The keyboard interrupt never reaches your outer try/except block.键盘中断永远不会到达您的外部 try/except 块。

You want to escape the while loop, exceptions inside the while block are handled here:你想跳出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

if you break from the loop on keyboard interrupt you leave the while loop and wont grab again.如果您在键盘中断时退出循环,您将离开 while 循环并且不会再次抓取。

Use the following code to fix your problem:使用以下代码解决您的问题:

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