python - 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 循环?让我知道你们的想法
解决方案
- Python列表有问题,所以你可以使用
if json_resp:
- 您可以使用递归。只要确保你有地方可以休息
我想将您的代码修改为:
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()
推荐阅读
- git - 如何在 Visual Studio 中通过 Git 将项目移动到另一个文件夹
- python - 数据框:ValueError:一个系列的真值不明确
- python - 如何将 np 数组转换为 StringIO
- python - 我如何控制opencv中的帧?
- amazon-web-services - 使用 withCredentials 时被 cors 拒绝,设置了访问控制允许凭据和来源
- c++ - 文件模式标志“ios::app”是否用于删除已存在的文件?
- python - 如何从元组列表的第二项中获取最小的项?
- java - 带有时区和毫秒的 LocalDateTime 格式
- python - 无法运行测试脚本。PyCharm Selenium Python 测试
- dart - Dart:将 int 转换为 int Function()