在以下代码中,
import platform
import signal
import threading
import time
class TimeoutListener(object):
def __init__(self, timeout_seconds, error_message="Timeout executing."):
self.timeout_seconds = timeout_seconds
self.error_message = error_message
self.alarm = None
def __enter__(self):
signal.signal(signal.SIGALRM, self._handle_timeout)
signal.alarm(int(self.timeout_seconds))
def __exit__(self, listener_type, value, traceback):
# Disable the alarm.
if self.alarm:
self.alarm = None
else:
signal.alarm(0)
def _handle_timeout(self, signum, frame):
print ("Got the signum %s with frame: %s" % (signum, frame))
raise ValueError(self.error_message)
class TimedExecutor(object):
@staticmethod
def execute(timeout_secs, functor, *args, **kwargs):
msg = "Timeout executing method - %s." % functor.__name__
timeout_signal = TimeoutListener(timeout_secs, error_message=msg)
try:
with timeout_signal:
output = functor(*args, **kwargs)
except Exception as ex:
print("%s did not complete in %s: %s."
% (functor.__name__, timeout_secs, repr(ex)))
raise
return output
def foo():
for _ in range(10):
try:
time.sleep(1)
print("SLEEPING")
except Exception as ex:
print ex
ob = TimedExecutor.execute(1, foo)
我有TimedExecutor
类,当函数在给定的超时时间内没有完成执行时会引发错误。当foo定义如下时,代码工作正常(即在超时时引发错误):
def foo():
try:
for _ in range(10):
time.sleep(1)
print("SLEEPING")
except Exception as ex:
print ex
然而,如果在{try / except中写入foo
的相同代码,则不会引发任何错误(继续执行)。如何在不对foo进行任何更改的情况下使其引发错误?
答案 0 :(得分:0)
在foo函数实现中将print ex
更改为raise
。