函数调用的超时我正在用Python调用一个函数,我知道这个函数可能会停止并迫使我重新启动脚本。如何调用该函数,或者如何将其封装,以便如果需要超过5秒的时间,脚本就会取消它并执行其他操作。
3 回答
千万里不及你
TA贡献1784条经验 获得超9个赞
In [1]: import signal# Register an handler for the timeoutIn [2]: def handler(signum, frame):
...: print "Forever is over!"
...: raise Exception("end of time")
...: # This function *may* run for an indetermined time...In [3]: def loop_forever():
...: import time ...: while 1:
...: print "sec"
...: time.sleep(1)
...:
...: # Register the signal function handlerIn [4]: signal.signal(signal.SIGALRM, handler)Out[4]: 0# Define a timeout for your
functionIn [5]: signal.alarm(10)Out[5]: 0In [6]: try:
...: loop_forever()
...: except Exception, exc:
...: print exc ....: sec
sec
sec
sec
sec
sec
sec
secForever is over!end of time# Cancel the timer if the function returned before timeout# (ok, mine won't but yours maybe will :)In [7]:
signal.alarm(0)Out[7]: 0alarm.alarm(10)
请注意
def loop_forever(): while 1: print 'sec' try: time.sleep(10) except: continue
添加回答
举报
0/150
提交
取消
