subprocess.Popen和缓冲进程输出

时间:2011-02-09 16:38:38

标签: python fortran gfortran

从python代码中,我想运行一个从stdin获取其参数的二进制程序。使用子进程模块,这应该是直截了当的:

import subprocess
command = [ 'my_program' ]
p = subprocess.Popen( command,  \
        stdin = subprocess.PIPE, stdout = subprocess.PIPE, \
        env={ "GFORTRAN_UNBUFFERED_ALL": "1"} )
p.stdin.write ( stdin_stuff )
while True:
  o = p.stdout.readline()
  if p.poll() != None: 
    break
  # Do something with stdout

现在,这将启动该程序,但python脚本只是挂起。我明白这可能是因为gfortran(我用来编译my_program是缓冲它的stdout流.gfortran允许我使用GFORTRAN_UNBUFFERED_ALL环境变量,就像我一样,以及使用fortran代码中的FLUSH()内在函数,但仍然没有运气:python代码仍然挂起。

2 个答案:

答案 0 :(得分:4)

使用Popen.communicate()将字符串发送到进程“stdin而不是手动写入它应该会更好运。”

stdoutdata, stderrdata = p.communicate(stdin_stuff)

答案 1 :(得分:2)

补充Aphex's answer,这里是documentation的相关部分:

  

警告

     

使用communicate()而不是.stdin.write.stdout.read.stderr.read来避免由于任何其他操作系统管道缓冲区填满并阻止子进程而导致的死锁。