python子进程不写入标准输出

python子进程不写入标准输出,python,subprocess,Python,Subprocess,如果我运行以下python代码(在Python2.7中),我会得到一个空的输出文件,而我希望得到一行。怎么了 import subprocess with open('outfile.out', 'w') as out: pp=subprocess.Popen(['/bin/cat'],stdin=subprocess.PIPE,stdout=out) pp.stdin.write('Line I want into out file\n') pp.terminate()

如果我运行以下python代码(在Python2.7中),我会得到一个空的输出文件,而我希望得到一行。怎么了

import subprocess

with open('outfile.out', 'w') as out:
   pp=subprocess.Popen(['/bin/cat'],stdin=subprocess.PIPE,stdout=out)
   pp.stdin.write('Line I want into out file\n')
   pp.terminate()

终止
d进程,并且从未刷新/关闭对它的输入,因此所有数据都被卡在缓冲区中,并在强制终止进程时被丢弃。您可以使用
communicate
组合传递的输入,关闭
stdin
,然后等待过程完成:

import subprocess

with open('outfile.out', 'w') as out:
   pp=subprocess.Popen(['/bin/cat'],stdin=subprocess.PIPE,stdout=out)
   pp.communicate('Line I want into out file\n')
在这种情况下(三个标准手柄中只有一个是管道),您也可以安全地执行此操作:

import subprocess

with open('outfile.out', 'w') as out:
   pp=subprocess.Popen(['/bin/cat'],stdin=subprocess.PIPE,stdout=out)
   pp.stdin.write('Line I want into out file\n')
   pp.stdin.close()
   pp.wait()  # Optionally with a timeout, calling terminate if it doesn't join quickly

只有当您仅使用一个标准句柄作为
管道
;如果有多个是
管道
,则存在死锁的风险(child正在写入stdout,等待您读取以清除缓冲区,您正在写入stdin,等待child读取以清除缓冲区),
使用线程或选择模块进行通信
解决死锁,您必须模仿这种设计以避免死锁。

使用
pp.wait()
而不是
pp.join()
(它是
子流程,而不是
多处理
)。Python 2.7中没有
timeout
参数(除非您使用
subprocess32
模块)。@J.F.Sebastian:修复了
wait
join
位之间的差异;您的评论可以澄清
timeout
何时可用。