1

I checked out Reading stdout from one program in another program but did not find the answer I was looking for

I'm new to Linux and i'm using the argparse module in Python to run arguments with a program through the terminal on my Mac

I have program_1.py that inputs a file via sys.stdin and outputs data to sys.stdout

I'm trying to get program_2.py to take in this data that was outputted to sys.stdout from program_1.py and take it in as it's sys.stdin

I tried something along the lines of:

Mu$ python program-1.py <sample.txt> program-2.py 

For simplicity, let's say that 'sample.txt' just had the string '1.6180339887'

How can program_2.py read from sys.stdout of the previous program as it's sys.stdin?

In this simple example, I am just trying to get program_2.py to output '1.6180339887' to sys.stdout so I can see how this works.

Somebody told me to use the | character for pipelines but I couldn't make it work correctly

Community
  • 1
  • 1
O.rka
  • 29,847
  • 68
  • 194
  • 309
  • to avoid prefixing `python` each time, you could add at the very top [`#!/usr/bin/env python` line (shebang)](http://stackoverflow.com/q/2429511/4279) and set executable permissions for the script: `chmod +x program_1.py`. After that, you could run the script as `./program_1.py` – jfs Oct 30 '14 at 00:53

2 Answers2

2

Using a pipe is correct:

python program-1.py sample.txt | python program-2.py 

Here's a complete example:

$ cat sample.txt                                                             
hello                                                                        

$ cat program-1.py                                                           
import sys                                                                   
print open(sys.argv[1]).read()                                               

$ cat program-2.py                                                           
import sys                                                                   
print("program-2.py on stdin got: " + sys.stdin.read())                      

$ python program-1.py sample.txt                                             
hello                                                                        

$ python program-1.py sample.txt | python program-2.py                       
program-2.py on stdin got: hello  

(PS: you could have included a complete test case in your question. That way, people could say what you did wrong instead of writing their own)

that other guy
  • 116,971
  • 11
  • 170
  • 194
0

program-1.py:

import sys

if len(sys.argv) == 2:
    with open(sys.argv[1], 'r') as f:
        sys.stdout.write(f.read())

program-2.py:

import sys

ret = sys.stdin.readline()
print ret

sample.txt

1.6180339887

in your shell:

Mu$ python p1.py txt | python p2.py

output:

1.6180339887

more info here: http://en.wikipedia.org/wiki/Pipeline_(Unix) and here http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output