Python Asyncio子进程永远不会完成

时间:2014-07-02 21:18:06

标签: python python-asyncio

我有一个简单的python程序,我用它来测试子进程的asyncio:

import sys, time
for x in range(100):
    print("processing (%s/100)    " % x)
    sys.stdout.flush()
print("enjoy")
sys.stdout.flush()

在命令行上运行它会产生所需的结果。

然而,当从asyncio调用时,它永远不会完成

process = yield from asyncio.create_subprocess_exec(
    *["python", "program.py"],
    stdout=async_subprocess.PIPE,
    stderr=async_subprocess.STDOUT,
    cwd=working_dir
)

# this never finishes
yield from process.communicate()

ps ax显示此过程为<defunct>,不确定这意味着什么

1 个答案:

答案 0 :(得分:10)

我怀疑您的问题与您拨打asyncio.create_subprocess_execprocess.communiate()的方式有关。这个完整的例子适合我:

import asyncio
from asyncio import subprocess

@asyncio.coroutine
def do_work():
    process = yield from asyncio.create_subprocess_exec(
        *["python", "program.py"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )

    stdout, _= yield from process.communicate()
    print(stdout)

if __name__  == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_work())

您必须在yield from内放置使用asyncio.coroutine的代码,然后在事件循环内调用它(使用loop.run_until_complete),以使其按您希望的方式运行到。