Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将数据从python管道传输到外部命令_Python_Subprocess_External Process_Piping - Fatal编程技术网

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

将数据从python管道传输到外部命令,python,subprocess,external-process,piping,Python,Subprocess,External Process,Piping,我已经阅读了子流程的所有内容。波本,但我想我遗漏了一些东西 我需要能够执行一个unix程序,该程序从python脚本中创建的列表中读取数据流,并将该程序的结果写入文件。从bash提示符开始,我一直在做这件事,没有问题,但现在我试图从一个python脚本中对此进行解释,该脚本在进入这个阶段之前预处理一些二进制文件和大量数据 让我们看一个不包括所有预处理的简单示例: import sys from pylab import * from subprocess import * from shlex

我已经阅读了子流程的所有内容。波本,但我想我遗漏了一些东西

我需要能够执行一个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程序的方式也很重要,我应该将其格式化为两列,以空格分隔


非常感谢您的帮助……

像这样的服务怎么样

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

print process.communicate()

您需要设置输入格式以正确进行通信

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])
解决了

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

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()

这非常有效,谢谢。

命令中
您将输出重定向到
输出文件
,但随后您尝试使用
通信
将其读入程序。您希望输出到何处?使用“>”不是将输出重定向到文件的方法,请参阅以下回答:是的,您的回答是正确的(两人)但我认为我的问题在这之前就开始了:我使用了'>'重定向,但这是shell重定向,无效。@Shahar您可以在Popen构造函数中使用
shell=True
参数来允许shell重定向,但是
communicate
不会为stdout返回任何内容。另一个选项是打开一个文件
f=open('outfile','w')
,然后使用
stdout=f
代替
PIPE
。我不确定现在的问题是什么,我还建议您在调用Popen之外创建file对象,以便以后在您和您的子流程完成后可以对其调用
.close()