1

I want to print the output on webpage as soon as the print statement is executed. Here is my code:

#!/usr/bin/python2.7
import sys, time    
sys.stdout.write('Content-Type: text/html\n')
sys.stdout.write('\n\n')
print "<html><body>"
print "hi"
sys.stdout.flush()
for i in range(10):
    print '<div>%i</div>'%i
    sys.stdout.flush()
    time.sleep(1)
print "</body></html>"

But I see all output at once only after full script is executed. Am I missing anything?

9
  • 1
    See stackoverflow.com/questions/1645308/… for more information. (It uses Perl, but the underlying principles still apply.) Commented Nov 29, 2016 at 21:17
  • @John Gordon, it dint help. Commented Nov 30, 2016 at 0:39
  • I am still unable to resolve the issue, sys.stdout.flush doesn't seem to be working in my case, it will be great if someone can suggest any other solutions? Commented Dec 2, 2016 at 21:38
  • I think the problem is that your browser waits until it gets all the output before displaying anything. Commented Dec 2, 2016 at 21:45
  • I tried in all 3, firefox, chrome and IE, but in none of them, it worked. Not sure what can be the solution. Commented Dec 2, 2016 at 21:54

1 Answer 1

1

You may need to disable apache compression that requires to buffer the whole content before sending it to the browser.

Try to add this in the /etc/apache2 configuraton file:

<Directory /var/www/your_web_site_here>
    SetEnv no-gzip 1
</Directory>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.