一篇简单demo带你走进async
import asyncio
import time
import requests
async def ntest2(i):
r = await other_ntest(i) #等待other_ntest 执行完成
print(f"ntest2:{i}:{r}")
async def other_ntest(i):
r = requests.get(i)
print(f"other_ntest:{i}")
await asyncio.sleep(14)
print(time.time() - start)
return r
url = ["https://segmentfault.com/p/1210000013564725",
"https://www.jianshu.com/p/83badc8028bd",
"https://www.baidu.com/"]
loop = asyncio.get_event_loop() #创建一个循环
task = [asyncio.ensure_future(ntest2(i)) for i in url] #创建任务
start = time.time()
loop.run_until_complete(asyncio.wait(task)) #检测task运行情况并返回结果
endtime = time.time() - start
print(endtime)
loop.close()#关闭循环