timer python generator
From Noah.org
Jump to navigationJump to search
This is the easiest way to run some code in a loop with a time-out. When the timeout is reached the loop will stop iterating.
#!/usr/bin/env python def timer(duration): '''This is a generator that stops after the given duration in seconds. Through each iteration it yields the time left. If the time left is negative then the generator has ended. The amount of negative time left represents how long over the duration the generator was when it ended. Long over time end results are caused be delays in the outer loop. Example, a 3.25 second timer: for time_left in timer(3.25): print (time_left) print ("Finished %f seconds overtime." % (-1 * time_left) ) ''' import time end_time = time.time() + duration time_left = duration while time_left > 0.0: yield time_left time_left = end_time - time.time() yield time_left if __name__ == '__main__': import sys import time for time_left in timer(5): sys.stdout.write('\033[1G') # CHA: cursor to column 1 sys.stdout.write('%06.4f' % time_left) sys.stdout.flush() time.sleep(0.1) sys.stdout.write('\033[1G') # CHA: cursor to column 1 sys.stdout.write('%06.4f' % time_left) print ("Finished %f seconds overtime." % (-1 * time_left) ) sys.stdout.write('\ndone\n') # vim:set ft=python fileencoding=utf-8 sr et ts=4 sw=4 : See help 'modeline'