【问题标题】:Python - If json.object is empty, repeat the function until new value?Python - 如果 json.object 为空,重复该函数直到新值?
【发布时间】:2018-08-31 09:46:47
【问题描述】:

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

基本上我有一个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 循环?让我知道你们的想法

【问题讨论】:

    标签: python if-statement try-catch


    【解决方案1】:
    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多