Skip to content

Instantly share code, notes, and snippets.

@evanthebouncy
Last active March 21, 2016 08:34
Show Gist options
  • Save evanthebouncy/1f2095abeb6c5c651d24 to your computer and use it in GitHub Desktop.
Save evanthebouncy/1f2095abeb6c5c651d24 to your computer and use it in GitHub Desktop.
=========== put this in timeout.py ==============
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.setitimer(signal.ITIMER_REAL,seconds) #used timer instead of alarm
try:
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return wraps(func)(wrapper)
return decorator
=========== put this as test.py in samem folder as timeout.py ============
from timeout import *
@timeout(0.1)
def f ( x0 ) :
x1 = [ ]
x2 = [ 0.0 ]
while x1 < x2 :
if x1 == 0 :
x3 [ 0 ] = 0.0
elif x1 == 1 :
x3 . append ( x0 [ x1 ] )
else :
for x2 in range ( 1 , len ( x0 ) ) :
x3 . append ( x0 [ x1 ] * ( x1 - 1 ) )
x1 = x1 + 1
return x3
f([1,2,3,4,5])
@timeout(0.1)
def g ():
x = 1
while True:
x = x % 2
g()
============= work around (wtf) =============
@timeout(0.1)
def f1 ( x0 ) :
print "1"
x1 = [ ]
print "2"
x2 = [ 0.0 ]
print "3"
while x1 < x2 :
print "4"
if x1 == 0 :
print "5"
x3 [ 0 ] = 0.0
print "6"
elif x1 == 1 :
print "7"
x3 . append ( x0 [ x1 ] )
print "8"
else :
print "9"
for x2 in range ( 1 , len ( x0 ) ) :
print "10"
x3 . append ( x0 [ x1 ] * ( x1 - 1 ) )
print "11"
x1 = x1 + 1
print "12"
return x3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment