Skip to content

Instantly share code, notes, and snippets.

@papisz
Created May 13, 2014 13:09
Show Gist options
  • Save papisz/1913a0f4f4c8eaebae2b to your computer and use it in GitHub Desktop.
Save papisz/1913a0f4f4c8eaebae2b to your computer and use it in GitHub Desktop.
Python timeout snippet
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Taken from:
http://stackoverflow.com/a/22348885
http://stackoverflow.com/a/2282656"""
import signal
class TimeoutError(Exception):
pass
class timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
@papisz
Copy link
Author

papisz commented May 13, 2014

Usage:

from timeout import timeout

with timeout(seconds=3):
    sleep(4)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment