为什么大多数 asyncio 示例都使用 loop.run_until_complete()? [英] Why do most asyncio examples use loop.run_until_complete()?

查看:524
本文介绍了为什么大多数 asyncio 示例都使用 loop.run_until_complete()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览 asyncio 的 Python 文档,我想知道为什么大多数示例使用 loop.run_until_complete() 而不是 Asyncio.ensure_future().

I was going through the Python documentation for asyncio and I'm wondering why most examples use loop.run_until_complete() as opposed to Asyncio.ensure_future().

例如:https://docs.python.org/dev/library/asyncio-task.html

ensure_future 似乎是展示非阻塞函数优势的更好方式.run_until_complete 另一方面,像同步函数一样阻塞循环.

It seems ensure_future would be a much better way to demonstrate the advantages of non-blocking functions. run_until_complete on the other hand, blocks the loop like synchronous functions do.

这让我觉得我应该使用 run_until_complete 而不是 ensure_futureloop.run_forever() 的组合来运行多个 co- 例程并发.

This makes me feel like I should be using run_until_complete instead of a combination of ensure_futurewith loop.run_forever() to run multiple co-routines concurrently.

推荐答案

run_until_complete 用于运行未来直到它完成.它将阻止其后代码的执行.但是,它确实会导致事件循环运行.任何已安排的期货都将运行,直到传递给 run_until_complete 的期货完成.

run_until_complete is used to run a future until it's finished. It will block the execution of code following it. It does, however, cause the event loop to run. Any futures that have been scheduled will run until the future passed to run_until_complete is done.

以这个例子为例:

import asyncio

async def do_io():
    print('io start')
    await asyncio.sleep(5)
    print('io end')

async def do_other_things():
    print('doing other things')

loop = asyncio.get_event_loop()

loop.run_until_complete(do_io())
loop.run_until_complete(do_other_things())

loop.close()

do_io 将运行.完成后,do_other_things 将运行.您的输出将是:

do_io will run. After it's complete, do_other_things will run. Your output will be:

io start
io end
doing other things

如果在运行 do_io 之前用事件循环安排 do_other_things,控制将从 do_io 切换到 do_other_things当前者等待时.

If you schedule do_other_things with the event loop before running do_io, control will switch from do_io to do_other_things when the former awaits.

loop.create_task(do_other_things())
loop.run_until_complete(do_io())

这将为您提供以下输出:

This will get you the output of:

doing other things
io start
io end

这是因为 do_other_things 是在 do_io 之前安排的.有很多不同的方法可以获得相同的输出,但哪种方法有意义实际上取决于您的应用程序实际执行的操作.所以我将把它留给读者作为练习.

This is because do_other_things was scheduled before do_io. There are a lot of different ways to get the same output, but which one makes sense really depends on what your application actually does. So I'll leave that as an exercise to the reader.

这篇关于为什么大多数 asyncio 示例都使用 loop.run_until_complete()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆