我在Python中有一个使用子过程和comunicate()
的脚本,但我无法成功访问stdout
和stderr
。当我仅使用stdin
时,脚本效果很好。这是脚本的一部分:
proc = subprocess.Popen(["./a.out"],
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
def inp(self,txt):
f=open(txt,"r")
self.proc.communicate(f.read()) #this works well!!
print self.proc.stdout.read #this doesn't work
#or
stdout_value=self.proc.communicate()
print stdout_value #this doesn't work
#self.result.communicate()[1]
stderr
也是同样的麻烦。如何读取输出和stderr
?
.communicate()
等待子过程完成。它最多可以一次称为。
.communicate()
如果相应的stdout,stderr参数为 PIPE
s。
除非您需要它,否则不要使用shell=True
。
您可以直接提供文件:
from subprocess import Popen, PIPE
with open(filename, 'rb', 0) as input_file:
p = Popen(['./a.out'], stdin=input_file, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
请参阅文档,communicate()
返回您正在调用时正确的内容。当您通过
inp()
方法中的第二行时,您会得到它 stdout_value, stderr_value = self.proc.communicate(f.read())
注意:如果您期望将大量数据返回,则communicate()
不是您的最佳选择:数据在内存中进行了缓冲,因此您可能会遇到麻烦。取而代之的是,您最好将输入权转移到self.proc.stdin
,然后在可管理的块中处理self.proc.stdout
。