读取/写入 Popen() 子进程

2022-01-18 00:00:00 python subprocess popen python-2.6

问题描述

我正在尝试使用 python subprocess.Popen() 调用与子进程交谈.在我的真实代码中,我正在实现一种 IPC,所以我想写入一些数据、读取响应、写入更多数据、读取响应等等.因此,我不能使用 Popen.communicate(),否则它适用于简单的情况.

I'm trying to talk to a child process using the python subprocess.Popen() call. In my real code, I'm implementing a type of IPC, so I want to write some data, read the response, write some more data, read the response, and so on. Because of this, I cannot use Popen.communicate(), which otherwise works well for the simple case.

这段代码显示了我的问题.它甚至从来没有得到第一个响应,挂在第一个阅读结果"上.为什么?我怎样才能使这项工作如我所愿?

This code shows my problem. It never even gets the first response, hangs at the first "Reading result". Why? How can I make this work as I expect?

import subprocess
p = subprocess.Popen(["sed", 's/a/x/g'],
                     stdout = subprocess.PIPE,
                     stdin = subprocess.PIPE)

p.stdin.write("abc
")
print "Reading result:"
print p.stdout.readline()

p.stdin.write("cat
")
print "Reading result:"
print p.stdout.readline()


解决方案

如果可以的话,我会尝试使用 Popen().communicate(),因为它为你做了很多好事,但是如果您需要完全按照您的描述使用 Popen(),则需要使用 -l 选项将 sed 设置为在换行符之后刷新其缓冲区:

I would try to use Popen().communicate() if you can as it does a lot of nice things for you, but if you need to use Popen() exactly as you described, you'll need to set sed to flush its buffer after newlines with the -l option:

p = subprocess.Popen(['sed', '-l', 's/a/x/g'],
                     stdout=subprocess.PIPE,
                     stdin=subprocess.PIPE)

你的代码应该可以正常工作

and your code should work fine

相关文章