Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear stdout in Python after flush()

I'm trying to make my Python script stream its output to my webpage as its printed.

So in my javascript I do:

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 what I get is 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4

It seems to be sending the whole buffer each time, when what I really want is for it to send one digit per onreadystatechange.

What am I doing wrong?

like image 781
Jeff Avatar asked Jun 13 '26 00:06

Jeff


1 Answers

xmlhttp.responseText on the client side always contains the entire response, so you don't need newbody, just use xmlhttp.responseText.

like image 182
Tamás Avatar answered Jun 15 '26 23:06

Tamás