1.安装模块

pip install func_timeout

2.导入模块

from func_timeout import func_set_timeout

3.使用例子

        加5秒超时:

import time
from func_timeout import func_set_timeout


@func_set_timeout(5)
def timer():
    for num in range(1,11):
        time.sleep(1)
        print(num)

timer()

        结果:

1
2
3
4
Traceback (most recent call last):
  File "C:/Users/Bek/Desktop/weston/hayaya.py", line 11, in <module>
    timer()
  File "C:\Users\Bek\Desktop\weston\venv\lib\site-packages\func_timeout\dafunc.py", line 185, in <lambda>
    return wraps(func)(lambda *args, **kwargs : func_timeout(defaultTimeout, func, args=args, kwargs=kwargs))
  File "C:\Users\Bek\Desktop\weston\venv\lib\site-packages\func_timeout\dafunc.py", line 101, in func_timeout
    raise FunctionTimedOut('', timeout, func, args, kwargs)
func_timeout.exceptions.FunctionTimedOut: Function timer (args=()) (kwargs={}) timed out after 5.000000 seconds.


Process finished with exit code 1

        加15秒超时 函数能正常跑完:

1
2
3
4
5
6
7
8
9
10

Process finished with exit code 0

4.添加捕获异常

import time
from func_timeout import func_set_timeout
import func_timeout

@func_set_timeout(5)
def timer():
    for num in range(1,11):
        time.sleep(1)
        print(num)

try:
    timer()
except func_timeout.exceptions.FunctionTimedOut as e:
    print(e)
    print("Time out!!!")

        结果:

1
2
3
4
Function timer (args=()) (kwargs={}) timed out after 5.000000 seconds.

Time out!!!

Process finished with exit code 0