需求背景
在python代码的实现中,假如我们有一个需要执行时间跨度非常大的for循环,如果在中间的某处我们需要定时停止这个函数,而不停止整个程序。那么初步的就可以想到两种方案:第一种方案是我们先预估for循环或者while中的每一步所需要的运行时间,然后设定在到达某一个迭代次数之后就自动退出循环;第二种方案是,在需要设置超时任务的前方引入超时的装饰器,使得超过指定时间之后自动退出函数执行。这里我们将针对第二种方案,进行展开介绍。
timeout-decorator的安装
在pypi的标准库中也包含有timeout-decorator
模块,因此可以通过pip
来直接安装:
[dechin@dechin-manjaro timeout]$ python3 -m pip install timeout_decorator
Collecting timeout_decorator
Downloading timeout-decorator-0.5.0.tar.gz (4.8 kB)
Building wheels for collected packages: timeout-decorator
Building wheel for timeout-decorator (setup.py) ... done
Created wheel for timeout-decorator: filename=timeout_decorator-0.5.0-py3-none-any.whl size=5029 sha256=279f8585a08d5e5c87de887492169d1a81e02060c8ea3b62fdd6f062b7f83601
Stored in directory: /home/dechin/.cache/