将数据从python传递到外部命令

Sha*_*har 5 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))
Run Code Online (Sandbox Code Playgroud)

在bash中执行的方式是:

echo "11 31
      13 33
      15 37
      16 35
      17 38
      18 39.55" | my_unix_prog option1 option2 .... > outfile
Run Code Online (Sandbox Code Playgroud)

数据输入到unix prog的方式也很重要,我应该格式化为两列,并用空格隔开。

任何帮助表示赞赏...

Sha*_*har 5

解决了!

在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()
Run Code Online (Sandbox Code Playgroud)

这非常有效,谢谢。