从Python进行Stdin重定向

时间:2013-03-26 22:37:08

标签: python io-redirection

假设我有一个名为some_binary的程序可以将数据读取为:

some_binary < input

其中input通常是磁盘中的文件。我想将input从Python 发送到some_binary而不写入磁盘

例如input通常是包含以下内容的文件:

0 0.2
0 0.4
1 0.2
0 0.3
0 0.5
1 0.7

要在Python中模拟类似的东西,我有:

import numpy as np

# Random binary numbers
first_column = np.random.random_integers(0,1, (6,))

# Random numbers between 0 and 1
second_column = np.random.random((6,))

如何将first_columnsecond_column的连接提供给some_binary,就好像我从命令行调用some_binary < input,并收集stdout一样一个字符串?

我有以下内容:

def run_shell_command(cmd,cwd=None,my_input):
      retVal = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=my_input, cwd=cwd);
      retVal = retVal.stdout.read().strip('\n');
      return(retVal);

但我不确定我是朝着正确的方向前进。

1 个答案:

答案 0 :(得分:1)

是的,你正朝着正确的方向前进。

您可以使用pythons subprocess.check_output()函数,它是subprocess.Popen()周围的便利包装器。 Popen需要更多基础架构。例如,您需要在comminucate()的返回值上调用Popen才能使事情发生。

这样的东西
output = subprocess.check_output([cmd], stdin = my_input)

应该适用于您的情况。

相关问题