首先,我运行这样的代码,重试工作正常。
# -*- coding:utf-8 -*-
from retrying import retry
import asyncio
import time
num = 0;
def retry_if_result_none(result):
return result is None
@retry(retry_on_result=retry_if_result_none)
def get_result():
global num;
num += 1;
if num < 10:
print('Retry.....');
return None;
else:
return True;
time.sleep(1);
def call():
end = get_result();
if end:
print('ok');
else:
print('over')
if __name__ == '__main__':
call();
Output:
Retry.....
Retry.....
Retry.....
Retry.....
Retry.....
Retry.....
Retry.....
Retry.....
Retry.....
ok
其次,我像这样编辑代码,然后再次运行,但收到不同的结果。
# -*- coding:utf-8 -*-
from retrying import retry
import asyncio
import time
num = 0;
def retry_if_result_none(result):
# print("retry_if_result_none")
return result is None
@retry(retry_on_result=retry_if_result_none)
async def get_result():
global num;
num += 1;
if num < 10:
print('Retry.....');
return None;
else:
return True;
time.sleep(1);
async def call():
end = await get_result();
if end:
print('ok');
else:
print('over')
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(call())
Output:
Retry.....
over
如图所示,重试在第二个代码中不起作用。不同之处在于我将 call() 放在 loop.run_until_complete 方法中,如何解决这个问题?