Skip to content

Instantly share code, notes, and snippets.

@Phxntxm
Created June 27, 2020 22:33
Show Gist options
  • Save Phxntxm/3e1bfccbbaa9fd8f685587d824b62319 to your computer and use it in GitHub Desktop.
Save Phxntxm/3e1bfccbbaa9fd8f685587d824b62319 to your computer and use it in GitHub Desktop.
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