Last active
September 14, 2015 13:30
-
-
Save goulu/45329ef041a368a663e5 to your computer and use it in GitHub Desktop.
multiplatform timeout for loops in Python
This file contains hidden or 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
from threading import Timer | |
from multiprocessing import TimeoutError | |
def itimeout(iterable,timeout): | |
"""timeout for loops | |
:param iterable: any iterable | |
:param timeout: float max running time in seconds | |
:yield: items in iterator until timeout occurs | |
:raise: multiprocessing.TimeoutError if timeout occured | |
""" | |
timer=Timer(timeout,lambda:None) | |
timer.start() | |
for i in iterable: | |
yield i | |
if timer.finished.is_set(): | |
raise TimeoutError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
can anybody turn this into a decorator that could be used as: