def exec_timed(code, context, timeout_secs):
"""
Dynamically execute 'code' using 'context' as the global enviroment.
SafeEvalTimeoutException is raised if execution does not finish within
the given timelimit.
"""
assert(timeout_secs > 0)
signal_finished = False
def alarm(secs):
def wait(secs):
for n in xrange(timeout_secs):
time.sleep(1)
if signal_finished: break
else:
thread.interrupt_main()
thread.start_new_thread(wait, (secs,))
try:
alarm(timeout_secs)
exec code in context
signal_finished = True
except KeyboardInterrupt:
raise SafeEvalTimeoutException(timeout_secs)
评论列表
文章目录