While循环with time.sleep

时间:2019-07-19 10:33:01

标签: python python-3.x

我将使用while循环刷新方法。

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,它将显示为错误。如果将其置于while循环下,它将不断更新,并且不会等待5分钟。

我不知道错误在哪里。我希望你能帮助我。

2 个答案:

答案 0 :(得分:3)

您需要导入python时间库

如果您放置

import time

它应该在文件顶部

答案 1 :(得分:1)

您是否已导入time库?如果不是,则添加

import time

位于代码顶部,它应该可以正常工作。

还请记住,输出缓冲可能会出现问题,程序将无法按预期等待,因此您需要将其关闭,如this answer所示。