在Python中flush()后清除stdout

3 投票
1 回答
837 浏览
提问于 2025-04-16 19:29

我正在尝试让我的Python脚本把输出实时发送到我的网页上。

所以在我的JavaScript代码里,我写了:

var xmlhttp;
var newbody = "";
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==3) {
      newbody = newbody + xmlhttp.responseText;
      document.getElementById("new").innerHTML=newbody;
    }
}
xmlhttp.open("GET","http://localhost/cgi-bin/temp.py",true);
xmlhttp.send();

而在我的Python脚本中,我有:

print "Content-Type: text/plain"
print ""
print " " * 5000   # garbage data for safari/chrome
sys.stdout.flush()

for i in range(0,5):
    time.sleep(.1)
    sys.stdout.write("%i " % i)
    sys.stdout.flush()

现在我期待看到 0 1 2 3 4,但我得到的是 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4

看起来每次都在发送整个缓冲区,而我真正想要的是每次只发送一个数字,等到状态改变时就发送。

我哪里做错了?

1 个回答

3

在客户端,xmlhttp.responseText 总是包含了完整的响应内容,所以你不需要什么 newbody,直接使用 xmlhttp.responseText 就可以了。

撰写回答