将数据从python管道传输到外部命令

时间:2012-08-06 14:10:32

标签: python subprocess external-process piping

我已经阅读了subprocess.Popen上的所有内容,但我想我错过了一些东西。

我需要能够执行一个unix程序,该程序从python脚本中创建的列表中读取数据流,并将该程序的结果写入文件。从bash提示符开始,我一直这样做没有问题,但现在我正在尝试从python脚本中进行此操作,该脚本在进入此阶段之前预处理一些二进制文件和大量数据。

让我们看一个不包括所有预处理的简单示例:

import sys
from pylab import *
from subprocess import *
from shlex import split

# some arbitrary x,y points
points = [(11,31),(13,33),(15,37),(16,35),(17,38),(18,39.55)]

commandline = 'my_unix_prog option1 option2 .... > outfile'
command = split(commandline)

process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
print process.communicate(str(points))

在bash中执行的方式是:

echo "11 31
      13 33
      15 37
      16 35
      17 38
      18 39.55" | my_unix_prog option1 option2 .... > outfile

将数据输入unix prog的方式也很重要,我应该格式化为由空格分隔的2列。

感谢任何帮助...

3 个答案:

答案 0 :(得分:3)

解决!

Dharaxhainingx的帮助下,我能够解决这个问题:

import sys
from pylab import *
from subprocess import *
from shlex import split

# some arbitrary x,y points
points = [(11,31),(13,33),(15,37),(16,35),(17,38),(18,39.55)]

commandline = 'my_unix_prog option1 option2 ....'
command = split(commandline)

process = Popen(command, stdin=PIPE, stdout=open('outfile', 'w'), stderr=PIPE)
for p in points:
    process.stdin.write(str(p[0]) + ' ' + str(p[1]) + '\n')

print process.communicate()

这非常有效,谢谢。

答案 1 :(得分:1)

这样的东西
for p in points:
    process.stdin.write(str(p[0]) + ' ' + str(p[1]) + '\n')

print process.communicate()

答案 2 :(得分:0)

您需要格式化输入才能正确通信。

当您打印不符合要求的元组列表时,

str将保留特殊字符。

>>> print str([(1,2), (3,4)]) 
[(1,2), (3,4)]

试试这个:

print process.communicate("\n".join(["%s %s"%(x[0], x[1]) for x in points])