1

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. I followed this question and added the except KeyboardInterrupt: statement. It again takes a screenshot when I press CTRL+C. Can someone help with this?

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40

2 Answers2

2

You need to move your keyboard interrupt exception handling one up. The keyboard interrupt never reaches your outer try/except block.

You want to escape the while loop, exceptions inside the while block are handled here:

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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

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)
abhigyanj
  • 2,355
  • 2
  • 9
  • 29