使用python设置超时
我想调用一个自己写的方法def getData:
但是getData有时候会取不出数据
因此我想设置个超时,如果getData 5秒钟没有响应,那么就触发超时,程序自动exit
timeout(5,getData)
请问在python中怎么写,还是python本身就有这个方法
------解决方案--------------------@TraceFunc
def WorkInTime(Func, Timeout = 0, *args):
'''
If function cann't finished in time then timeout
'''
def handler(signum, frame):
raise AssertionError
try:
signal.signal(signal.SIGALRM, handler)
signal.alarm(Timeout)
ret = Func(*args)
signal.alarm(0)
return ret
except AssertionError:
logger.error("%s conn't finished in %d seconds, timeout!" % (Func.__name__, Timeout))
return -1
------解决方案--------------------
@TraceFunc
def WorkInTime(Func, Timeout = 0, *args):
'''
If function cann't finished in time then timeout
'''
def handler(signum, frame):
raise AssertionError
try:
signal.signal(signal.SIGALRM, handler)
signal.alarm(Timeout)
ret = Func(*args)
signal.alarm(0)
return ret
except AssertionError:
logger.error("%s conn't finished in %d seconds, timeout!" % (Func.__name__, Timeout))
return -1