Print the output of os.popen () without buffering in python

Let's say that I have a process that outputs some data similar to this ruby ​​code.

1.upto(10) { 
  |i| 
  puts i 
  puts "\n" 
  sleep 0.6 
} 

I want to have python code that starts this process and reads data from it in order to print it.

import os 
import sys 
cmd = "ruby /Users/smcho/Desktop/testit.rb"; 
pingaling = os.popen(cmd,"r") 
while 1: 
    line = pingaling.readline() 
    if not line: break 
    print line, 
    sys.stdout.flush() 
pingaling.close() 

The problem with this code is that it does not print number one after another. It looks like python is outputting all buffered data at the last point.

Is there a way to print the output of a spawned process without buffering?

+3
source share
1 answer

Data is buffered by ruby. Use something like

$stdout.flush

to make it smooth. I'm not sure the correct ruby ​​command is for this.


Required:

subprocess. os.popen .

import subprocess
import sys

cmd = ["ruby", "/Users/smcho/Desktop/testit.rb"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, ''):
    print line, 
    sys.stdout.flush() 
p.wait()
+5

Source: https://habr.com/ru/post/1733711/


All Articles