0

I'm trying to pipe the output of a python script using os.popen() . Here my python script :

sample.py

while(True):
   print("hello")

python version : 3.6.7 os : ubuntu 18.04

My script to do the process :

import os
import types
def sample_function():
    pipe = os.popen('python3 /home/gomathi/sample.py')
    while(True):
        a = pipe.readline()
        yield a
s=sample_function()
for i in s:
    print(i)

It works well for the above code.Now the problem is , i have changed the sample.py as follows :

sample.py

print("hello")

It just print blank for the entire screen and continues printing blank characters . What went wrong with my code ? What changes to be made in my code to work for the above sample.py ?

1
  • 2
    Use the subprocess module. The docs come with many examples. Commented Jun 10, 2019 at 7:15

2 Answers 2

2

Your new sample.py ends, but you keep reading from the pipe. So you're getting empty strings.

Sign up to request clarification or add additional context in comments.

Comments

0

Use the subprocess module, with the same function Popen and redirect the output and the error to the print function of your main .py file.

from subprocess import Popen, PIPE
command = ['python3', '/home/gomathi/sample.py']
process = Popen(command, shell=False, stdout=PIPE, stdin=PIPE)
while True:
    line = process.stdout.readline() #variable_name_changed
    print(line)

2 Comments

I'm getting error in stdout (undefined variable) in line 5
My fault, I wrote an equal sign = instead of a point .. Solved, now, it should works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.