Clear stdout in Python after flush ()

I am trying to make my Python script stream my output to my web page as printed.

So, in my javascript, I:

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

and in my Python script I have:

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

Now I expect 0 1 2 3 4, but I get0 0 1 0 1 2 0 1 2 3 0 1 2 3 4

It seems that every time it sends the entire buffer, when I really want it to send one digit for each request.

What am I doing wrong?

+3
source share
1 answer

xmlhttp.responseTexton the client side always contains the whole answer, so you don’t need to newbody, just use xmlhttp.responseText.

+3
source

All Articles