更新时间:2021-10-05 23:30:41
我不确定这可能是跨平台的,但使用信号和警报可能是看待这个问题的好方法.只需稍加努力,您就可以使其完全通用,并可在任何情况下使用.
I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.
http://docs.python.org/library/signal.html
所以你的代码看起来像这样.
So your code is going to look something like this.
import signal
def signal_handler(signum, frame):
raise Exception("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10) # Ten seconds
try:
long_function_call()
except Exception, msg:
print "Timed out!"