Timed execution in eval
castironpi at gmail.com
castironpi at gmail.com
Fri Mar 7 16:15:04 EST 2008
On Mar 7, 10:12 am, alex.pedwyso... at gmail.com wrote:
> I have various bits of code I want to interpret and run at runtime in
> eval ...
import sys
from time import clock, sleep
from threading import Timer
TimeoutError= type('TimeoutError',(Exception,),{})
class Elapse:
def __init__( self ):
self.flag= False
def set( self ):
self.flag= True
def tr( frame, event, arg ):
if elapse.flag:
raise TimeoutError
return tr
def sleeper():
while 1:
sleep( .3 )
print( 'tick' )
def factercomp( n ):
val= 1
for i in range( 1, n ):
val*= i
return val
def facter( n ):
print( factercomp( n ) )
def runit( f, *ar ):
global elapse
elapse= Elapse()
t= Timer( 1, elapse.set )
t.start()
sys.settrace( tr )
try:
f( *ar )
except TimeoutError:
print( 'time elapse' )
runit( sleeper )
runit( facter, 10 )
runit( facter, 20 )
runit( facter, 10000 )
runit( facter, 100000 )
'''
tick
tick
tick
time elapse
362880
121645100408832000
time elapse
time elapse
'''
More information about the Python-list
mailing list