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')
a