Python:重试直到发生变化
Python: retry till something change
我不明白这个简单的代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
for val in "cacatcaca":
try:
if val == "c":
print(val)
time.sleep(0.5)
if val == "a":
print(val)
time.sleep(0.5)
except val == "t":
print('We are stock in the letter T')
time.sleep(0.5)
continue
结果是:
c
a
c
a
c
a
c
a
而我想要的是在 't'
获得库存直到时间结束:
c
a
c
a
We are stock in the letter T
We are stock in the letter T
We are stock in the letter T
...
...
...
我的目标是在收到 ['status'] == 'OVER_QUERY_LIMIT'
时重用 Google API 的代码。
我想继续尝试 JSON
回复,直到收到不同的回复。
您在这里错误地使用了 try-catch 块。
您应该将所有条件放在 try 块下的 if-else 语句中
如果有任何异常,则打印出来。
for val in "cacatcaca":
try:
if val == "c":
print(val)
time.sleep(0.5)
elif val == "a":
print(val)
time.sleep(0.5)
elif val=="t":
print('We are stock in the letter T')
time.sleep(0.5)
except Exception as e:
print(e)
continue
此代码将打印 "We are stock at the letter t" 直到时间结束。
import time
for val in 'cacatcaca':
if val == 'c' or val == 'a':
print(val)
time.sleep(0.5)
elif val == 't':
while val == 't':
print('We are stock at letter t')
对于可重用的设计,我更愿意使用基于此类代码的解决方案:
def fetch_google_api_until_works(*args, **kwargs):
ok = False
while not ok:
response = legacy_fetch_google_api(*args, **kwargs)
ok = response.get('status', False) != 'OVER_QUERY_LIMIT'
if not ok:
time.sleep(0.5)
return response
然后在您的应用代码中使用 fetch_google_api_until_works
。
我不明白这个简单的代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
for val in "cacatcaca":
try:
if val == "c":
print(val)
time.sleep(0.5)
if val == "a":
print(val)
time.sleep(0.5)
except val == "t":
print('We are stock in the letter T')
time.sleep(0.5)
continue
结果是:
c
a
c
a
c
a
c
a
而我想要的是在 't'
获得库存直到时间结束:
c
a
c
a
We are stock in the letter T
We are stock in the letter T
We are stock in the letter T
...
...
...
我的目标是在收到 ['status'] == 'OVER_QUERY_LIMIT'
时重用 Google API 的代码。
我想继续尝试 JSON
回复,直到收到不同的回复。
您在这里错误地使用了 try-catch 块。
您应该将所有条件放在 try 块下的 if-else 语句中 如果有任何异常,则打印出来。
for val in "cacatcaca":
try:
if val == "c":
print(val)
time.sleep(0.5)
elif val == "a":
print(val)
time.sleep(0.5)
elif val=="t":
print('We are stock in the letter T')
time.sleep(0.5)
except Exception as e:
print(e)
continue
此代码将打印 "We are stock at the letter t" 直到时间结束。
import time
for val in 'cacatcaca':
if val == 'c' or val == 'a':
print(val)
time.sleep(0.5)
elif val == 't':
while val == 't':
print('We are stock at letter t')
对于可重用的设计,我更愿意使用基于此类代码的解决方案:
def fetch_google_api_until_works(*args, **kwargs):
ok = False
while not ok:
response = legacy_fetch_google_api(*args, **kwargs)
ok = response.get('status', False) != 'OVER_QUERY_LIMIT'
if not ok:
time.sleep(0.5)
return response
然后在您的应用代码中使用 fetch_google_api_until_works
。