Created
June 27, 2020 22:33
-
-
Save Phxntxm/3e1bfccbbaa9fd8f685587d824b62319 to your computer and use it in GitHub Desktop.
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 signal | |
def timeout(func, duration, *args, **kwargs): | |
""" | |
Handles timing out a function | |
Parameters | |
---------- | |
func | |
The callable to call | |
args: | |
The positional arguments to pass to the function call | |
kwargs: | |
The keyword arguments to pass to the function call | |
duration: :class:`int` | |
The amount in seconds to wait before timing out | |
Returns | |
------- | |
The result from the function called | |
Raises | |
------ | |
TimeoutException | |
""" | |
if args is None: | |
args = () | |
if kwargs is None: | |
kwargs = {} | |
def handler(signum, frame): | |
raise TimeoutError() | |
signal.signal(signal.SIGALRM, handler) | |
signal.alarm(duration) | |
try: | |
return func(*args, **kwargs) | |
finally: | |
signal.alarm(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment