尝试重新运行函数,直到它使用请求在python中返回特定值



我正在运行一个获取请求,该请求正在检索特定服务器进程的状态,我希望在脚本中重新运行该请求,直到状态返回完成,以便在脚本中执行后续功能。

到目前为止,我所拥有的代码包括一个执行get请求以获取当前状态的函数,以及一个while循环,只要返回",就应该重新运行该函数;"待定";但它并没有按预期工作。

def get_status(id, token):
url = "exampleurl.com/status"
headers = {'Authorization' : 'Bearer ' + token}
response = requests.request("GET", url, headers=headers)
resp_dict = json.loads(response.text)
current_status = resp_dict['status']
return current_status
while status(id, key) == 'PENDING':
status(id, key)
if status(id, key) == 'FINISHED':
print('its done')

我认为最好使用答案部分来修复代码,而不是添加注释。

首先,感谢您对代码所做的更改。现在看起来好多了。

在函数定义中,返回语句具有print(current_status)。当您返回打印语句时,它将始终返回None

将您的代码更改为:

return current_status

当您更改函数名称时,留下While循环调用旧函数。您需要将其更改为get_status(id,key(。请注意,可以通过检查get_status(id, key) != 'FINISHED'来优化while循环

此代码的第三个问题是没有更改id和key的值。那么,你预计结果会如何改变呢。它不是总是PENDING导致无限循环吗?

while status(id, key) == 'PENDING':
status(id, key)
if status(id, key) == 'FINISHED':
print('its done')

我建议你做一些改变,这样你就能得到更好的结果。

你可以这样做:

while True:
#you need to have a way to get new id & key
if get_status(id, key) == 'FINISHED': 
print('its done')
break

备用,你可以这样做:

id = xxx #whatever the value
key = yyy #whatever the value
while get_status(id, key) != 'FINISHED':
#add code to change the value of id & key

这将继续用id和key的新值调用函数,直到它得到"FINISHED"的状态结果

最新更新