is it possible to give a simple example showing how async / await
works, by using only these two keywords + asyncio.get_event_loop() +
run_until_complete + other Python code but no other asyncio functions?
这样就可以编写有效的代码:
import asyncio
async def main():
print('done!')
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
但这样就无法证明为什么需要asyncio.
顺便说一句,为什么你需要asyncio,而不仅仅是简单的代码?答案是 – 当您并行化I / O阻塞操作(如读/写网络)时,asyncio允许您获得性能优势.要编写有用的示例,您需要使用这些操作的异步实现.
有关详细说明,请阅读this answer.
UPD:
好的,这是使用asyncio.sleep来模仿I / O阻塞操作的示例,以及asyncio.gather,它显示了如何同时运行多个阻塞操作:
import asyncio
async def io_related(name):
print(f'{name} started')
await asyncio.sleep(1)
print(f'{name} finished')
async def main():
await asyncio.gather(
io_related('first'),
io_related('second'),
) # 1s + 1s = over 1s
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
输出:
first started
second started
first finished
second finished
[Finished in 1.2s]
注意两个io_related如何在一秒钟之后开始,两者都完成了.
本文提供了一个简单的Python异步编程示例,使用async/await关键字以及asyncio库的get_event_loop和run_until_complete方法。通过模拟I/O阻塞操作,展示了如何利用asyncio.gather实现并发执行任务,提高性能。在示例中,两个模拟I/O任务在1秒内并行完成,展示了异步编程的优势。
386

被折叠的 条评论
为什么被折叠?



