Last active
June 27, 2016 00:21
-
-
Save waylan/9aba33507d596b5d3acdd3775b0fc264 to your computer and use it in GitHub Desktop.
Countdown timer starts from `start_value` and counts down to zero, then counts up with negated time. Only displays minutes and seconds. No pause or reset available.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from threading import Timer | |
def now(): | |
""" Return the current time in seconds since the epoch. """ | |
return int(time.time()) | |
class Countdown(object): | |
""" | |
Countdown timer starts immediatly on init from `start_value` and counts down | |
to zero, then counts up with negated time. Only displays minutes and | |
seconds. No pause or reset available. Each "tick" of the clock is passed to | |
the callback function as a string. """ | |
def __init__(self, start_value, callback): | |
self._finished = False | |
self.start_value = start_value | |
self.callback = callback | |
self.start_time = now() | |
self._update() | |
def _update(self): | |
self._set_time(now() - self.start_time) | |
if not self._finished: | |
self._timer = Timer(1, self._update) | |
self._timer.start() | |
def _set_time(self, value): | |
neg = '' | |
if self.start_value > value: | |
value = self.start_value - value | |
elif self.start_value < value: | |
value = value - self.start_value | |
neg = '-' | |
else: | |
value = 0 | |
mm, ss = divmod(value, 60) | |
self.callback("{}{:02d}:{:02d}".format(neg, mm, ss)) | |
def stop(self): | |
self._timer.cancel() | |
self._finished = True | |
if __name__ == '__main__': | |
from sys import stdout, argv | |
# Codes are here: http://www.termsys.demon.co.uk/vtansi.htm | |
RED, GREEN, YELLOW = 31, 32, 33 | |
def callback(t): | |
""" Replace previous string written to console with new string. """ | |
color = RED if t.startswith('-') else YELLOW if t.startswith('00') else GREEN | |
stdout.write('\rCountdown: \033[{0};1m{1}\033[0m'.format(color, t.lstrip('-'))) | |
stdout.flush() | |
if len(argv) > 1: | |
for arg in argv[1:]: | |
mm, ss = arg.split(':') | |
c = Countdown((int(mm) * 60) + int(ss), callback) | |
raw_input(' Press [enter] to stop.') | |
c.stop() | |
else: | |
print 'No time provided to count down from. Use `mm:ss`.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment