1、Windows中sign报错,Linux能很好的使用:
https://pypi.python.org/pypi/timeout-decorator
import time
import timeout_decorator
@timeout_decorator.timeout(5)
def mytest():
print("Start")
for i in range(1,10):
time.sleep(1)
print("{} seconds have passed".format(i))
if __name__ == '__main__':
mytest()
import timeout_decorator
@timeout_decorator.timeout(5)
def mytest():
print("Start")
for i in range(1,10):
time.sleep(1)
print("{} seconds have passed".format(i))
if __name__ == '__main__':
mytest()
2、Windows可以使用,Linux报错不能导入包
https://pypi.python.org/pypi/func_timeout
from func_timeout import func_set_timeout, FunctionTimedOut
@func_set_timeout(2.5)
def mytest2():
print("Start")
for i in range(1, 10):
print("%d seconds have passed" % i)
time.sleep(10)
if __name__ == '__main__':
try:
mytest2()
except FunctionTimedOut as e:
print('mytest2:::', e)
@func_set_timeout(2.5)
def mytest2():
print("Start")
for i in range(1, 10):
print("%d seconds have passed" % i)
time.sleep(10)
if __name__ == '__main__':
try:
mytest2()
except FunctionTimedOut as e:
print('mytest2:::', e)
调用函数时捕获异常,可以在程序暂停时产生作用。
3、Windows、Linux都可以使用的
https://pypi.python.org/pypi/stopit
import stopit
@stopit.threading_timeoutable()
def infinite_loop():
# As its name says...
try:
print("Start")
for i in range(1, 10):
print("%d seconds have passed" % i)
time.sleep(10)
except Exception as e:
traceback.print_exc()
if __name__ == '__main__':
infinite_loop(timeout=1)
@stopit.threading_timeoutable()
def infinite_loop():
# As its name says...
try:
print("Start")
for i in range(1, 10):
print("%d seconds have passed" % i)
time.sleep(10)
except Exception as e:
traceback.print_exc()
if __name__ == '__main__':
infinite_loop(timeout=1)
超时会抛出异常,我们可以设置 try except 捕获。
程序运行中可以抛出异常。如果暂停或者卡住,就无效了。