如何使用 popen 创建管道并在 Python 中通过它进行通信



我有一个写入标准输出并从标准输入的进程。我想,在Python中,使用该过程从其stdout/stdin读取和写入。

我试过了:

      process = Popen(['the_program_name'], stdout=PIPE, stderr=PIPE, stdin=PIPE)

然后我尝试使用

      process.stdout.readline()

      process.stdin.write('input to the_program_name')

但这行不通...

有什么想法吗?

编辑:

程序似乎在 Readline 语句上阻塞,在 write 语句之后。如果我使用 process.communication,那么我会得到输出,但外部进程会立即终止。

在这里阅读:

相关代码:

import subprocess
print 'npopen2:'
proc = subprocess.Popen(['cat', '-'],
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        )
stdout_value = proc.communicate('through stdin to stdout')[0]
print 'tpass through:', repr(stdout_value)

最新更新