在 x 时间后中断 while 循环,但在同一级别继续 for 循环

Break while loop after x amount of time but continue for loop at the same level

目前我正在使用一些 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 收到新令牌后开始

您真的不需要 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])

好的,所以我认为您的意思是随时都可以获取新令牌,但您想每 9 分钟尝试一次:

import time

end_time = time.time() - 1  # force end_time to be invalid at the start
for repetition in range(0, 4):
    ##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]:
                if time.time() > end_time:
                    end_time = time.time() + 60*9
                    sw_patcher_ghp = Shopware()
                    bearer_token_ghp = sw_patcher_ghp.get_access_token()

                print(sw_patcher_ghp.patch_ruleid(bearer_token_ghp, all_json[i][1], all_csv[ii][1], true_boolean), 'GHP', all_json[i][1])