Python Forum
ticktock generator and command
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ticktock generator and command
#2
yes, line 7 was totally useless. it looks to me like leftover from an edit that quietly didn't break anything. i have removed it, now.

ticktock.py:
import time
_mt=dict(s=1,m=60,h=60*60,d=60*60*24,w=60*60*24*7)
def ticktock(offset=0,cycle=60): # default is top of every minute
    """Generator to sleep to each time stop in a time sequence without acculated errors."""
    # example: wake up every 5 minutes at 1 minute in: ticktock(60,300)
    while True:
        s=(offset-time.time())%cycle
        time.sleep(s)
        yield s
def _tc(s):
    try:
        return float(s)
    except ValueError:
        return float(s[:-1])*_mt[s[-1]]
if __name__=='__main__':
    import sys
    g=ticktock(*[_tc(x)for x in sys.argv[1:]])
    try:
        while True:
            next(g)
            print('tick',flush=True)
            next(g)
            print('tock',flush=True)
    except KeyboardInterrupt:
        exit('')
    except Exception:
        exit()
this doesn't really need to be a generator. but it's a nice example and a starting point for making other things.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
ticktock generator and command - by Skaperen - Jul-10-2020, 01:19 AM
RE: ticktock generator and command - by Skaperen - Jul-10-2020, 05:17 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020