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

℡╲_俬逩灬. 提交于 2019-12-22 09:56:29

问题


Let's say that I have a process that prints out some data something like this ruby code.

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

I want to have a python code that spawns this process, and read data from it to print it out.

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 of this code is that it doesn't print the number one by one. It seems like that python prints out all the buffered data at the last point.

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


回答1:


The data is being buffered by ruby. Use something like

$stdout.flush

to make it flush. I'm not sure if that's the correct ruby command to do that.


Obligatory:

Use subprocess module. os.popen has been replaced by it.

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()


来源:https://stackoverflow.com/questions/2304072/print-out-the-output-of-os-popen-without-buffering-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!