问题描述
比方说,我有一个进程可以打印一些数据,例如红宝石代码.
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
}
我想要一个生成该过程的python代码,并从中读取数据以打印出来.
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()
此代码的问题是它不会一一打印出数字.好像python在最后一点打印出所有缓冲的数据.
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?
推荐答案
数据被ruby缓冲.使用类似的东西
The data is being buffered by ruby. Use something like
$stdout.flush
使其齐平.我不确定这是否是正确的ruby命令.
to make it flush. I'm not sure if that's the correct ruby command to do that.
必填:
使用subprocess
模块. os.popen
已替换通过它.
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()
这篇关于打印出os.popen()的输出而无需在python中进行缓冲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!