Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - how to pipe the output using popen?

Tags:

python

popen

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?

like image 831
sami Avatar asked Dec 27 '10 07:12

sami


2 Answers

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

)

like image 183
david van brink Avatar answered Oct 19 '22 23:10

david van brink


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()
like image 34
atx Avatar answered Oct 19 '22 23:10

atx