首页 > 解决方案 > Python - 如果 json.object 为空,重复该函数直到新值?

问题描述

所以我一直在尝试找到一种更漂亮的方法来在我正在处理的脚本中实际执行一些错误和错误。

基本上我有一个json_resp = resp.json()给我价值或[]意义的人,无论有没有。

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

我所做的是我将对象从 json resp 更改为 len。如果它为 0,则重复 else 做其他事情:

#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 循环?让我知道你们的想法

标签: pythonif-statementtry-catch

解决方案


  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()

推荐阅读