Created
July 22, 2022 16:01
-
-
Save Tbruno25/cadd6a47c0c09ab07a2faf83a4337a30 to your computer and use it in GitHub Desktop.
Simple python3 timeout
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
import time | |
from contextlib import contextmanager | |
from typing import Iterator | |
@contextmanager | |
def timeout(seconds: float = 5) -> Iterator: | |
""" | |
A simple context manager to enable timeouts. | |
Args: | |
seconds (float): Length of timeout in seconds. Defaults to 5 | |
Yields: | |
Iterator[bool]: True if timeout exceeded | |
Example: | |
with timeout(60) as t: | |
while True: | |
if t(): | |
# handle | |
""" | |
stop = time.time() + seconds | |
def timed_out(): | |
return time.time() > stop | |
yield timed_out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment