[英]Python Asyncio subprocess never finishes
i have a simple python program that I'm using to test asyncio with subprocesses: 我有一个简单的python程序,我用它来测试子进程的asyncio:
import sys, time
for x in range(100):
print("processing (%s/100) " % x)
sys.stdout.flush()
print("enjoy")
sys.stdout.flush()
Running this on the command line produces the desired results. 在命令行上运行它会产生所需的结果。
However, when called from asyncio, it never finishes 但是,从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
shows this process is <defunct>
, not sure what that means ps ax
显示此过程<defunct>
,不确定这意味着什么
I suspect your issue is just related to how you're calling asyncio.create_subprocess_exec
and process.communiate()
. 我怀疑你的问题与你如何调用
asyncio.create_subprocess_exec
和process.communiate()
。 This complete example works fine for me: 这个完整的例子适合我:
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())
You have to place code that uses yield from
inside of a asyncio.coroutine
, and then call it inside an event loop (using loop.run_until_complete
), for it to behave the way you want it to. 您必须在
asyncio.coroutine
放置使用yield from
代码,然后在事件循环内调用它(使用loop.run_until_complete
),以使其按照您希望的方式运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.