首页 > 解决方案 > 在 x 时间后中断 while 循环,但在同一级别继续 for 循环

问题描述

目前我正在使用一些 api,我必须在其中更新或删除数据。为了验证自己,我必须使用一些令牌,这些令牌的有效期为 10 分钟。

我的任务需要超过 10 分钟,所以我无法正常完成我的程序。

我对这个问题的解决方案是跟踪时间,在 9 分钟后,我想请求新的令牌并继续在我的 for 循环中停止的地方进行。

import time

end_time = time.time() + 60*9
while time.time() < end_time:
    for repetition in range(0, 4):
        sw_patcher_ghp = Shopware()
        bearer_token_ghp = sw_patcher_ghp.get_access_token()
        continue
        ##compare both files if skus are matching, grab the data which is needed for patching ruleIds
        for i in range(0, len(all_json)):
            for ii in range(0, len(all_csv)):
                if all_json[i][0] == all_csv[ii][0]:
                    print(sw_patcher_ghp.patch_ruleid(bearer_token_ghp, all_json[i][1], all_csv[ii][1], true_boolean), 'GHP', all_json[i][1])

现在最大的问题是:如何请求新令牌,但我还必须能够在我离开的地方继续 for 循环

例如,当我在 i = 500 离开时,我想在 501 收到新令牌后开始

标签: pythonpython-3.xfor-loopwhile-loopshopware

解决方案


你真的不需要while循环。如果 9 分钟过去了,只需在最里面的循环中请求一个新令牌并更新end_time

for repetition in range(0, 4):
    sw_patcher_ghp = Shopware()
    bearer_token_ghp = sw_patcher_ghp.get_access_token()
    
    for i in range(0, len(all_json)):
        for ii in range(0, len(all_csv)):
            if all_json[i][0] == all_csv[ii][0]:
                if end_time >= time.time():
                    #enter code here get new token
                    end_time = time.time()+60*9
                else:
                    print(sw_patcher_ghp.patch_ruleid(bearer_token_ghp, all_json[i][1], all_csv[ii][1], true_boolean), 'GHP', all_json[i][1])

推荐阅读