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)
完美运行(在Ubuntu18.04,python3),但键盘中断不起作用。我按照 this 问题添加了 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)
我制作了一个简单的脚本来每隔几秒截取屏幕截图并将其保存到文件中。 这是脚本:
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)
完美运行(在Ubuntu18.04,python3),但键盘中断不起作用。我按照 this 问题添加了 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)