2

从 python 代码内部,我想运行一个从标准输入获取参数的二进制程序。使用 subprocess 模块,这应该很简单:

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 正在缓冲其标准输出流。gfortran 允许使用 GFORTRAN_UNBUFFERED_ALL 环境变量,就像我所做的那样,以及在 fortran 代码中使用 FLUSH() 内在变量,但仍然没有运气:python 代码仍然挂起。

4

2 回答 2

4

您应该有更好的运气使用Popen.communicate()将字符串发送到进程'stdin而不是手动写入它。

stdoutdata, stderrdata = p.communicate(stdin_stuff)
于 2011-02-09T16:42:21.233 回答
2

为了补充Aphex 的回答,这里是文档的相关部分:

警告

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

于 2011-02-09T16:50:06.867 回答