There is a script that makes a screenshot every 10 seconds.

from PIL import Image, ImageGrab from datetime import datetime, date, time import sched, time import os if not os.path.exists('./screen'): os.makedirs('./screen') s = sched.scheduler(time.time, time.sleep) def do_something(sc): dt = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S") img = ImageGrab.grab() img.save('./screen/' + dt +".png", "PNG") s.enter(10, 1, do_something, (sc,)) s.enter(10, 1, do_something, (s,)) s.run() 

Is it possible to make a condition that a print("END") displayed on the screen before the completion of a forced script?

By force, I mean some kind of cycle, which, for example, at 18:00 will shut down the script itself and display print("END")

  • And how the script is completed by force? And the output on the screen implies the output to the console, from which the script was called before? - mkkik
  • one
    Depends what it means "before the completion of the forced . " If on Ctrl + C, add try/except KeyboardInterrupt around run (). You can still atexit module (only for normal output or test which signals it understands). - jfs
  • @jfs @mikkik By force, I meant some kind of cycle, which, for example, at 18:00 will shut down the script itself and display print("END") - OuFinx
  • So what is the problem to check the time during the execution of the script? - mkkik
  • What's the question? How s.enterabs() call? How is 18:00 in time. Time value turn? How to exit the script in callback (does sys.exit() ). - jfs

1 answer 1

To save the screen capture every 10 seconds to a separate file and exit after 6:00 pm local time:

 #!/usr/bin/env python3 import datetime as DT import time import pyscreenshot # $ pip install pyscreenshot pillow while DT.datetime.now().time() < DT.time(18, 0): # < 18:00 obey local clock time.sleep(10 - time.time() % 10) # sleep until the next 10 seconds boundary image = pyscreenshot.grab() filename = f'screenshot-{DT.datetime.utcnow():%Y%m%d%H%M%S}Z.png' image.save(filename) print(filename) print("END") 

UTC time is used in file names, as local time may be non-monotonic.

See. How to make a temporary cycle?


To print the END and exit the s.run() loop in your code today at 6 pm local time, it is enough to s.enterabs(..) before s.run() :

 import sys from datetime import time as datetime_time def do_exit(): print("END") sys.exit() end_time = datetime.combine(datetime.now(), datetime_time(18, 0)) s.enterabs(end_time.timestamp(), 2, do_exit)