Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96428

Stdin redirection from Python

Say I have a program called some_binary that can read data as:

some_binary < input

where input is usually a file in disk. I would like to send input to some_binary from Python without writing to disk.

For example input is typically a file with the following contents:

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

To simulate something like that in Python I have:

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

How can I feed the concatenation of first_column and second_column to some_binary as if I was calling some_binary < input from the command line, and collect stdout in a string?

I have the following:

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

But I am not sure I am heading in the right direction.

Upvotes: 0

Views: 239

Answers (1)

Johannes Overmann
Johannes Overmann

Reputation: 5161

Yes, you are heading in the right direction.

You can use pythons subprocess.check_output() functions which is a convenience wrapper around subprocess.Popen(). The Popen needs more infrastructure. For example you need to call comminucate() on the return value of Popen in order for things to happen.

Something like

output = subprocess.check_output([cmd], stdin = my_input)

should work in your case.

Upvotes: 1

Related Questions