asyncio标准库1 Hello World

it2022-05-05  212

asyncio标准库1 Hello World

利用asyncio的event loop,编写和调度协程 coroutine [,kəuru:'ti:n] n. 协程

Simple coroutine(调用1个协程)

import asyncio async def say(what, when): await asyncio.sleep(when) print(what) loop = asyncio.get_event_loop() loop.run_until_complete(say('hello world', 1)) # 使用run_until_complete()方法,在协程完成后中断event loop。 loop.close()

Creating tasks(调用多个协程)

import asyncio async def say(what, when): await asyncio.sleep(when) print(what) loop = asyncio.get_event_loop() loop.create_task(say('first hello', 2)) loop.create_task(say('second hello', 1)) loop.run_forever() # 使用run_forever()方法,协程会一直运行,不会中断event loop loop.close()

Stopping the loop

import asyncio async def say(what, when): await asyncio.sleep(when) print(what) async def stop_after(loop, when): await asyncio.sleep(when) loop.stop() # 中断event loop loop = asyncio.get_event_loop() loop.create_task(say('first hello', 2)) loop.create_task(say('second hello', 1)) loop.create_task(say('third hello', 4)) loop.create_task(stop_after(loop, 3)) loop.run_forever() loop.close() # out: second hello first hello Task was destroyed but it is pending! task: <Task pending coro=<say() done, defined at e03.py:5> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7fed59595a68>()]>> # 在执行2个任务后,中断event loop,'third hello‘任务由于延迟时间4秒,未能执行。 posted on 2018-03-19 10:55 北京涛子 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/liujitao79/p/8600660.html


最新回复(0)