读取/写入Popen()子进程 [英] Reading/writing to a Popen() subprocess
问题描述
我正在尝试使用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\n")
print "Reading result:"
print p.stdout.readline()
p.stdin.write("cat\n")
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
这篇关于读取/写入Popen()子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!