在Python中利用timeout-decorator庫設置函數超時結束,具體方法如下:
1.首先,在Python中安裝timeout-decorator庫;
pip install timeout-decorator
2.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()