Skip to content

Instantly share code, notes, and snippets.

@embray
Created July 11, 2018 10:39
Show Gist options
  • Save embray/2186319d8e68158b40273684200706a8 to your computer and use it in GitHub Desktop.
Save embray/2186319d8e68158b40273684200706a8 to your computer and use it in GitHub Desktop.
root@b554a1ceecf7:/# cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04.4 LTS"
root@b554a1ceecf7:/# python3.6
Python 3.6.5 (default, May 3 2018, 10:08:28)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import signal
>>> from contextlib import contextmanager
>>> class TimeoutError(RuntimeError): pass
...
>>> @contextmanager
... def timeout(seconds):
... def handler(*args):
... raise TimeoutError("timed out after {} seconds".format(seconds))
... orig_handler = signal.signal(signal.SIGALRM, handler)
... signal.alarm(seconds)
... try:
... yield
... finally:
... signal.alarm(0)
... signal.signal(signal.SIGALRM, orig_handler)
...
>>> with timeout(3):
... 4 ** 5 ** 20
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 4, in handler
__main__.TimeoutError: timed out after 3 seconds
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment