python - 如果需要超过 5 秒,则传递一个函数
问题描述
但是,我在 for 循环中调用了一个函数,我想检查该函数的执行时间是否超过 5 秒,我想通过该迭代并继续进行下一次迭代。
我考虑过使用时间库,并启动一个时钟,但结束计时器只会在函数执行后执行,因此我将无法在 5 秒内通过该特定迭代
解决方案
我在下面附上一个例子。希望这可以帮助你:
from threading import Timer
class LoopStopper:
def __init__(self, seconds):
self._loop_stop = False
self._seconds = seconds
def _stop_loop(self):
self._loop_stop = True
def run( self, generator_expression, task):
""" Execute a task a number of times based on the generator_expression"""
t = Timer(self._seconds, self._stop_loop)
t.start()
for i in generator_expression:
task(i)
if self._loop_stop:
break
t.cancel() # Cancel the timer if the loop ends ok.
ls = LoopStopper( 5) # 5 second timeout
ls.run( range(1000000), print) # print numbers from 0 to 999999
推荐阅读
- spring-boot - Spring Boot:无法查找数据源
- if-statement - 如果单元格包含“?” 然后公式 X 如果不是则复制值
- java - 如何读取在其他 B 类步骤定义中以 A 类编写的背景步骤定义中获得的值?
- windows - 有哪些库可以在 Windows 上获得硬件加速的视频解码/编码?
- java - 数字主机模拟器中 Android 自动投影的本机视图
- python - 有没有办法将本地字典发送到 spark 集群?
- amazon-web-services - AWS-Lambda:无法添加另一个事件,无用的 GenerateChangeSet 失败消息
- java - com.sun.jdic 和 Flexdoc 库是否仍在 java 中使用?我们可以与 AAD 集成吗?
- visual-studio-2019 - 无法处理文件
.resx - python - 我可以在 python 中将表/数据框保存到文件(如 png/jpg)吗?