How to connect output using popen?

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

test.py

 while True: print"hello" 

a.py :

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

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

+7
source share
3 answers

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

You can use it as follows:

 from subprocess import Popen, PIPE output = Popen(['command-to-run', 'some-argument'], stdout=PIPE) print output.stdout.read() 
+14
source

Use the subprocess module, here is an example:

 from subprocess import Popen, PIPE proc = Popen(["python","test.py"], stdout=PIPE) output = proc.communicate()[0] 
+12
source

This will print only the first line of output:

a.py:

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

... and it 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 happens:

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

)

+2
source

All Articles