我遇到了一个非常简单的问题—我无法与进程的stdout通信. 这个过程是一个简单的秒表,所以我可以启动它,停止并得到当前时间.
秒表的代码是:
import argparse
import time
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('start', type=int, default=0)
start = parser.parse_args().start
while True:
print(start)
start += 1
time.sleep(1)
if __name__ == "__main__":
main()
它的管理者是:
import asyncio
class RobotManager:
def __init__(self):
self.cmd = ["python", "stopwatch.py", "10"]
self.robot = None
async def start(self):
self.robot = await asyncio.create_subprocess_exec(
*self.cmd,
stdout=asyncio.subprocess.PIPE,
)
async def stop(self):
if self.robot:
self.robot.kill()
stdout = await self.robot.stdout.readline()
print(stdout)
await self.robot.wait()
self.robot = None
async def main():
robot = RobotManager()
await robot.start()
await asyncio.sleep(3)
await robot.stop()
await robot.start()
await asyncio.sleep(3)
await robot.stop()
asyncio.run(main())
但stdout.readline
每次返回一个空字节串.
将stdout = await self.robot.stdout.readline()
更改为stdout, _ = await self.robot.communicate()
时,结果仍然是一个空字节串.
当在RobotManager.start
方法的末尾添加await self.robot.stdout.readline()
时,它将永远挂起.
但是,当删除stdout=asyncio.subprocess.PIPE
和所有readline
调用时,子进程会按预期打印到终端.
如何正确读取子进程stdout?