You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

While循环实现方法刷新时time.sleep使用异常问题求助

问题:Python while循环中time.sleep位置异常或无等待刷新问题

我计划使用while循环实现某API方法的刷新功能,编写代码如下:

def usagePerUserApi(): 
    while True: 
        url = .... 
        resp = requests.get(url, headers=headers, verify=False) 
        data = json.loads(resp.content) 
        code = resp.status_code 
        Verbindungscheck.ausgabeVerbindungsCode(code) 
        head =..... 
        table = [] 
        for item in (data['data']): 
            if item['un'] == tecNo: 
                table.append([ item['fud'], item['un'], str(item['lsn']), str(item['fns']), str(item['musage'])+"%", str(item['hu']), str(item['mu']), str(item['hb']), str(item['mb']) ]) 
        print(tabulate(table,headers=head, tablefmt="github")) 
        time.sleep(300)

当前遇到问题:将time.sleep(300)放在上述位置会报错;若将其置于while循环下(也就是循环的第一行),程序会持续刷新而不等待5分钟。不清楚问题根源,望获得技术帮助。


解决方案与问题分析

咱们一步步拆解你遇到的两个问题,帮你定位根源:

1. 放在当前位置报错的常见原因

你没给出具体错误信息,但大概率是这几个点:

  • 遗漏time模块导入:如果代码开头没写import time,调用time.sleep()肯定会抛出NameError,这是最容易忽略的细节。
  • 循环内代码抛出异常,没走到sleep步骤:比如API请求失败、data['data']不存在引发KeyError、tecNo未定义等,这些异常会直接中断循环,根本执行不到time.sleep()。

给你优化下代码,加上异常捕获和健壮性处理:

def usagePerUserApi(): 
    import time  # 确保导入time模块
    while True: 
        try:
            url = .... 
            resp = requests.get(url, headers=headers, verify=False) 
            resp.raise_for_status()  # 主动触发HTTP异常(比如404/500)
            data = resp.json()  # 用resp.json()替代json.loads更简洁健壮
            code = resp.status_code 
            Verbindungscheck.ausgabeVerbindungsCode(code) 
            head =..... 
            table = [] 
            # 用get避免data中无'data'键引发KeyError
            for item in data.get('data', []):  
                # 用get防止item中无'un'键
                if item.get('un') == tecNo:  
                    table.append([ 
                        item['fud'], item['un'], 
                        str(item['lsn']), str(item['fns']), 
                        f"{item['musage']}%",  # f-string更直观
                        str(item['hu']), str(item['mu']), 
                        str(item['hb']), str(item['mb']) 
                    ]) 
            print(tabulate(table, headers=head, tablefmt="github")) 
            time.sleep(300)
        except Exception as e:
            print(f"执行出错: {str(e)}")
            time.sleep(60)  # 出错后也等待一会儿再重试,避免频繁请求服务器

2. 放在循环第一行却无等待的排查方向

把time.sleep(300)放在while True:下一行,理论上第一次循环会先等5分钟再执行API请求,不会出现"持续刷新"的情况。可能的原因:

  • sleep参数写错:比如不小心写成time.sleep(0.3),那等待时间只有0.3秒,看起来就像没等待。仔细检查数值是否为300。
  • 交互式环境的线程问题:如果在Jupyter Notebook这类环境运行,可能存在线程阻塞导致sleep不生效,但这种情况很少见,换普通Python脚本运行试试。
  • 循环内代码触发了快速重试:如果异常捕获没处理好,可能出现报错后立刻重试的情况,让你误以为没等待。

总结建议

  1. 先确认import time已经添加;
  2. 用异常捕获包裹核心逻辑,确保错误不会中断整个循环,同时保证sleep能被执行;
  3. 用resp.json()和dict.get()提升代码容错性,减少意外报错;
  4. 如果还是有问题,把具体的错误信息贴出来,能更快定位问题。

内容的提问来源于stack exchange,提问作者Fabian Breuer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:45:11