繁体   English   中英

带中断的基本python while循环

[英]basic python while loop with break

我有一个基本的python问题。

我正在查询有时对时间敏感的 API。 我想在 python 中编写一个循环来实现这一点。 我想要的功能如下:

查询(返回r),如果查询成功返回则继续返回r。

如果没有,我想以增量方式向查询的参数添加一些时间(因此可能是 for 循环,for i in range(24 (hours)): 然后一次添加一小时,直到查询有效。

如果在上面的 for 循环之后查询不起作用,则有一些日志错误消息。

我正在努力使 while/for 循环的顺序正确。 我可以进行一些尝试,但我认为如果将其放入伪代码中会更有用:

While True:
  if (r is not successful):
    i = 0:
    while i <= 24:
    add time and query again
    r <-- return query with new time
    i += 1
.......
return r

像这样,当查询正确返回时如何退出循环?

我也不相信我的伪代码正是我想要的。

这能行吗?

def run_api():
    if success:
        return results
    else:
        return False

While True:
    results = run_api()
    if results:
        break
    else:
        sleep (however you have it coded)
return results

您可以使用 .time() 函数。

import time

while True:
    results = query()

    if results:
        print(results) #or return to any datatype as required.

        time.sleep(wait_period_to_next_query)   #to be given in seconds

        break #if you want to exit the loop after 1 successful query
    else:
        print('Query unsuccessful, retrying after wait period.')
        time.sleep(wait_period)    #wait_period to be given in seconds

如果要连续查询 API,可以省略断行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM