python subprocess不写入stdout

时间:2016-06-28 13:01:40

标签: python subprocess

如果我运行以下python代码(在python 2.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()

1 个答案:

答案 0 :(得分:2)

terminate进程,并且从不刷新/关闭它的输入,因此所有数据都被卡在缓冲区中并在进程被强制杀死时被丢弃。您可以使用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

只有在您使用单个标准句柄PIPE时才应该这样做;如果多个是PIPE,则存在死锁的风险(孩子正在写入stdout,等待你读取以清除缓冲区,你正在写入stdin,等待孩子读取以清除缓冲区) communicate通过使用线程或选择模块解决,您必须模仿该设计以避免死锁。