Python - 如果json.object为空,重复该函数直到新值?

问题描述 投票:-1回答:1

所以我一直试图找到一种更好的方法来实际在我正在处理的脚本中做一些错误和错误。

基本上我有一个json_resp = resp.json()谁给我价值或[]意味着有或没有。

现在我遇到麻烦的问题是,我不知道哪个方法最好重复一个函数,如果它是空的,我应该重复整个函数还是其他什么是“最好的理由”来解决它好办法?

我所做的是我将对象从json resp更改为len。如果它的0然后重复其他做其他的东西:

#json_resp['objects'] either has empty [] or not always.

json_resp = resp.json()

        if len(json_resp['objects']) == 0:
            print('Sleeping in 2 sec')
            time.sleep(2)
            run_method() #Shall I call the function to start over?

        else:
            print(len(json_resp['objects']))
            continue do rest of the code

正如你现在所看到的,我与json_resp的len相比,但是让我不确定的是,如果它是一个实际再次调用函数的好方法吗?它不会有限制或延迟整个过程...我不确定但你对使这个功能“更好,更聪明,更快”的想法是什么?

我的想法可能是要么尝试除了或while循环?让我知道你们的想法

python if-statement try-catch
1个回答
0
投票
  1. Python列表有问题,所以你可以使用if json_resp:
  2. 你可以使用递归。只要确保你有一个地方可以打破

我想将您的代码修改为:

max_iteration = 5
current_iteration = 0
def run_method():
    current_iteration += 1
    # Do other stuff. Requests I guess?
    response = resp.json
    if response:
        # do something with the response
    else:
        if current_iteration == max_iteration:
           return 'Maximum iterations reached: {}'.format(max_iteration)

        timer = 2
        print('Sleeping in {} seconds'.format(timer))
        time.sleep(timer)
        run_method()
© www.soinside.com 2019 - 2024. All rights reserved.