第一个程序
import asyncio
async def first():
print("first")
result=first()
print(result)
asyncio.run(result)
await + 可等待对象(协程对象,future,task)
task对象-在事件循环中添加多个任务
import asyncio
async def f():
print(1)
await asyncio.sleep(1)
print(2)
return 'f'
async def main():
print("main start")
task_list=[
asyncio.create_task(f(),name='f1'),
asyncio.create_task(f(),name='f2')
]
done,pending=await asyncio.wait(task_list,timeout=None) #done是集合,返回值对象
print(done)
asyncio.run(main())
future对象-task类的基类
不支持协程转换为协程可执行的方法
import asyncio
import time
def f():
print(1)
time.sleep(2)
print(2)
return "f"
async def main():
loop=asyncio.get_running_loop()
fus=[loop.run_in_executor(None,f),
loop.run_in_executor(None,f)] #None 可以传入线程池和进程池对象
result=await asyncio.wait(fus)
print(result)
asyncio.run(main())
例子
import asyncio
import requests
async def download(url):
loop = asyncio.get_event_loop()
fut=loop.run_in_executor(None,requests.get,url)
res=await fut
return res
urls=['u1','u2']
tasks=[
download(url) for url in urls
]
asyncio.run(asyncio.wait(tasks))
|