Python中如何让for循环在指定时间后自动continue并重新计数?

写了个 tumblr 的视频爬虫,vpn 掉了后即使重新连上网速恢复了,下载速度还是零点几 KB,用什么办法让指定时间后自动重新开始这个 for 循环?


Python中如何让for循环在指定时间后自动continue并重新计数?
8 回复

import time
while True:
****for xxxx
********do xxx
****time.sleep(60)


import time
from datetime import datetime, timedelta

def timed_loop_with_reset(total_iterations, timeout_seconds):
    """
    在指定时间内完成循环,超时则重置计数器重新开始
    
    Args:
        total_iterations: 需要完成的迭代次数
        timeout_seconds: 超时时间(秒)
    """
    start_time = datetime.now()
    completed_iterations = 0
    
    while completed_iterations < total_iterations:
        current_time = datetime.now()
        
        # 检查是否超时
        if (current_time - start_time).total_seconds() > timeout_seconds:
            print(f"超时!已过去 {(current_time - start_time).total_seconds():.1f}秒")
            print("重置计数器,重新开始...")
            completed_iterations = 0
            start_time = datetime.now()
            continue
        
        # 模拟每次迭代的工作
        try:
            # 这里替换成你的实际任务
            print(f"执行第 {completed_iterations + 1} 次迭代")
            time.sleep(0.5)  # 模拟耗时操作
            
            completed_iterations += 1
            
        except Exception as e:
            print(f"迭代出错: {e}")
            continue
    
    print(f"完成!总共执行了 {completed_iterations} 次迭代")

# 使用示例:尝试在3秒内完成10次迭代
if __name__ == "__main__":
    timed_loop_with_reset(total_iterations=10, timeout_seconds=3)

这个实现的核心逻辑是:

  1. 记录循环开始时间
  2. 每次迭代检查是否超时
  3. 超时则重置计数器并重新开始计时
  4. 正常完成指定次数后结束

关键点在于使用datetime.now()获取精确时间,通过计算时间差判断是否超时。continue语句确保超时后跳过当前迭代,重置计数器后重新开始循环。

如果你需要更精确的时间控制,可以考虑使用time.perf_counter()替代datetime

你写的这个 for 循环不执行完,time.sleep 应该不会执行吧

while 1
start = now
for
if now - start > 60
break
do

卡住的地方应该是 video = requests.get ()这块,这个判断语句放在里面应该不会执行到吧

#4 requests.get(timeout=1)

aiohttp + asyncio.Timeout ?

我记得 python 的 req 模块有 timeout 参数的,用 scrapy 也应该有 timeout 参数的

回到顶部