为什么 await 不等待 asyncio.create_subprocess_exec()

H.H*_*rry 2 python asynchronous coroutine python-asyncio

我正在编写一个协程来根据教程在 python 中执行 shell 命令。这里是基本的:

import asyncio

async def async_procedure():
    process = await asyncio.create_subprocess_exec('ping', '-c', '2', 'google.com')
    await process.wait()
    print('async procedure done.')

loop = asyncio.get_event_loop()
loop.run_until_complete(async_procedure())
loop.close()
Run Code Online (Sandbox Code Playgroud)

上面的这段代码工作得很好。它给出了这样的结果:

PING google.com (...) 56(84) bytes of data.
64 bytes from ...: icmp_seq=1 ttl=46 time=34.8 ms
64 bytes from ...: icmp_seq=2 ttl=46 time=34.5 ms

--- google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 33.771/34.437/34.881/0.407 ms
Process done!
Run Code Online (Sandbox Code Playgroud)

当我尝试删除 process.wait() 时:

async def async_procedure():
    await asyncio.create_subprocess_exec('ping', '-c', '2', 'google.com')
    print('async procedure done.')
Run Code Online (Sandbox Code Playgroud)

该脚本没有按预期工作:

Process done! # This line should be lastest line
PING google.com (...) 56(84) bytes of data.
64 bytes from ...: icmp_seq=1 ttl=46 time=21.1 ms
64 bytes from ...: icmp_seq=2 ttl=46 time=21.8 ms

--- google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 21.135/21.469/21.803/0.334 ms
Run Code Online (Sandbox Code Playgroud)

但是在一个非常相似的例子中没有问题:

async def async_procedure():
    await asyncio.sleep(2)
    print('async procedure done')
Run Code Online (Sandbox Code Playgroud)
  • 那么为什么 await 不等待 asyncio.create_subprocess_exec() 呢?

文档(https://docs.python.org/3/library/asyncio-task.html#coroutine)说:

result = await future 或 result = yield from future –暂停协程直到未来完成,然后返回未来的结果,或引发异常,该异常将被传播。(如果未来被取消,它会引发一个 CancelledError 异常。)请注意,任务是未来,关于未来的一切也适用于任务。

result = await coroutine or result = yield from coroutine –等待另一个协程产生结果(或引发异常,该异常将被传播)。协程表达式必须是对另一个协程的调用。

return 表达式 – 使用 await 或 yield from 向正在等待这个的协程产生一个结果。

引发异常 - 在协程中使用 await 或 yield from 在等待此异常的协程中引发异常。

  • 协程挂起等待时的实际流程是什么?

这里是 asyncio.create_subprocess_exec() 和 asyncio.sleep() 的源代码是协程。它们都是协程:

@coroutine
def create_subprocess_exec(program, *args, stdin=None, stdout=None,
                           stderr=None, loop=None,
                           limit=streams._DEFAULT_LIMIT, **kwds):
    if loop is None:
        loop = events.get_event_loop()
    protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
                                                        loop=loop)
    transport, protocol = yield from loop.subprocess_exec(
                                            protocol_factory,
                                            program, *args,
                                            stdin=stdin, stdout=stdout,
                                            stderr=stderr, **kwds)
    return Process(transport, protocol, loop)


@coroutine
def sleep(delay, result=None, *, loop=None):
    """Coroutine that completes after a given time (in seconds)."""
    if delay == 0:
        yield
        return result

    if loop is None:
        loop = events.get_event_loop()
    future = loop.create_future()
    h = future._loop.call_later(delay,
                                futures._set_result_unless_cancelled,
                                future, result)
    try:
        return (yield from future)
    finally:
        h.cancel()
Run Code Online (Sandbox Code Playgroud)

use*_*ica 9

您等待该过程开始。你没有等到它完成。await process.wait()等待它完成。

  • 我不敢相信这个问题如此简单。谢谢@user2357112! (2认同)