我有一个简单的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>
,不确定这意味着什么
答案 0 :(得分:10)
我怀疑您的问题与您拨打asyncio.create_subprocess_exec
和process.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
),以使其按您希望的方式运行到。