9

I want to pipe output of my file using popen, how can I do that?

test.py:

while True:
  print"hello"

a.py :

import os  
os.popen('python test.py')

I want to pipe the output using os.popen. how can i do the same?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
sami
  • 99
  • 1
  • 1
  • 2

3 Answers3

17

First of all, os.popen() is deprecated, use the subprocess module instead.

You can use it like this:

from subprocess import Popen, PIPE

output = Popen(['command-to-run', 'some-argument'], stdout=PIPE)
print output.stdout.read()
atx
  • 4,831
  • 3
  • 26
  • 40
  • 1
    The example shows this. You should use: Popen(['python', 'test.py'], stdout=PIPE) – atx Dec 27 '10 at 07:51
  • 1
    Per the subprocess documentaion [Here](https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate), and the other answer, proc.communicate()[0] should be used instead of stdout.read() to avoid deadlocking – storm_m2138 Oct 28 '14 at 22:21
12

Use the subprocess module, here is an example:

from subprocess import Popen, PIPE

proc = Popen(["python","test.py"], stdout=PIPE)
output = proc.communicate()[0]
ismail
  • 46,010
  • 9
  • 86
  • 95
  • 1
    it will hang until MemoryError happens. If the output is unlimited (as in the `test.py` case) then `.communicate()` shouldn't be used. Read incrementally using `proc.stdout` directly instead, see [Python: read streaming input from subprocess.communicate()](http://stackoverflow.com/a/17698359/4279) – jfs Jul 07 '16 at 23:52
4

This will print just the first line of output:

a.py:

import os
pipe = os.popen('python test.py')
a = pipe.readline()
print a

...and this will print all of them

import os
pipe = os.popen('python test.py')
while True:
    a = pipe.readline()
    print a

(I changed test.py to this, to make it easier to see what's going on:

#!/usr/bin/python
x = 0
while True:
    x = x + 1
    print "hello",x

)

david van brink
  • 3,604
  • 1
  • 22
  • 17