python,subprocess:从子进程读取输出

gru*_*czy 13 python subprocess stdout

我有以下脚本:

#!/usr/bin/python

while True:
    x = raw_input()
    print x[::-1]
Run Code Online (Sandbox Code Playgroud)

我叫它ipython:

In [5]: p = Popen('./script.py', stdin=PIPE)

In [6]: p.stdin.write('abc\n')
cba
Run Code Online (Sandbox Code Playgroud)

它工作正常.

但是,当我这样做时:

In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE)

In [8]: p.stdin.write('abc\n')

In [9]: p.stdout.read()
Run Code Online (Sandbox Code Playgroud)

口译员挂了.我究竟做错了什么?我希望能够多次写入和读取另一个进程,将一些任务传递给此进程.我需要做些什么不同的事情?

编辑1

如果我使用communicate,我得到这个:

In [7]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE)

In [8]: p.communicate('abc\n')
Traceback (most recent call last):
  File "./script.py", line 4, in <module>
    x = raw_input()
EOFError: EOF when reading a line
Out[8]: ('cba\n', None)
Run Code Online (Sandbox Code Playgroud)

编辑2

我试着冲洗:

#!/usr/bin/python

import sys

while True:
        x = raw_input()
        print x[::-1]
        sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

和这里:

In [5]: from subprocess import PIPE, Popen

In [6]: p = Popen('./script.py', stdin=PIPE, stdout=PIPE)

In [7]: p.stdin.write('abc')

In [8]: p.stdin.flush()

In [9]: p.stdout.read()
Run Code Online (Sandbox Code Playgroud)

但它再次挂起.

Dan*_*ach 15

我相信这里有两个问题:

1)您的父脚本调用p.stdout.read(),它将读取所有数据,直到文件结束.但是,您的子脚本在无限循环中运行,因此文件末尾永远不会发生.可能你想要p.stdout.readline()

2)在交互模式下,大多数程序一次只缓冲一行.从另一个程序运行时,它们可以缓冲更多.缓冲在许多情况下提高了效率,但是当两个程序需要交互式通信时会导致问题.

p.stdin.write('abc\n')加:

p.stdin.flush()
Run Code Online (Sandbox Code Playgroud)

在子进程脚本中,在print x[::-1]循环中添加以下内容之后:

sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

(import sys在顶部)

  • 将`sys.stdout.flush()`添加到脚本并使用`p.stdout.readline`终于有所帮助.非常感谢你的帮助. (2认同)