编辑:更接近于你已经拥有的东西,因为 asyncio 对于单个协程来说似乎有点过分了:
import sys
from subprocess import Popen, PIPE, STDOUT
args = (sys.executable, '-u', 'test4.py')
cmd = ' '.join(args)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, universal_newlines=True)
print("the process is running")
for line in iter(p.stdout.readline,''):
line = line.rstrip()
print(line)
原文:
我把东西扔在一起了。下面使用asyncio.subprocess 从子进程的输出中读取行,然后对它们进行处理(在这种情况下,只是print() 它们)。
子进程由args 指定,在我的例子中只是使用以下脚本(test4.py)以无缓冲模式运行另一个python实例:
import time
for _ in range(10):
print(time.time(), flush=True)
time.sleep(1)
我正在for 循环中睡觉,所以当程序完成时,很清楚这些行是单独进入还是同时进入。 (如果你不相信我,你可以把for循环改成while True:,这样永远不会结束。
“主管”脚本是:
import asyncio.subprocess
import sys
async def get_lines(args):
proc = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE)
while proc.returncode is None:
data = await proc.stdout.readline()
if not data: break
line = data.decode('ascii').rstrip()
# Handle line (somehow)
print(line)
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
loop = asyncio.get_event_loop()
args = (sys.executable, '-u', 'test4.py')
loop.run_until_complete(get_lines(args))
loop.close()
请注意,async def 是 Python 3.5+,but you could use @asyncio.coroutine in 3.4。