Difference between revisions of "timer python generator"
From Noah.org
Jump to navigationJump to searchm (Created page with 'Category: Engineering Category: Python 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. <pre…') |
m |
||
Line 1: | Line 1: | ||
− | [[Category: Engineering]] | + | [[Category:Engineering]] |
− | [[Category: Python]] | + | [[Category:Free_Software]] |
+ | [[Category:Python]] | ||
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. | 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. | ||
+ | |||
<pre> | <pre> | ||
#!/usr/bin/env python | #!/usr/bin/env python |
Revision as of 20:37, 19 December 2013
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. The duration may include fractional seconds such as "5.5". Example: for time_left in timer(10): print time_left ''' import time end_time = time.time() + duration time_left = duration while time_left > 0: yield time_left time_left = end_time - time.time() 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('\ndone\n')