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?

  • 1
    See http://stackoverflow.com/questions/1645308/how-can-i-continuously-inform-the-user-of-progress-from-a-perl-cgi-script for more information. (It uses Perl, but the underlying principles still apply.) – John Gordon Nov 29 '16 at 21:17
  • @John Gordon, it dint help. –  Nov 30 '16 at 00: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? –  Dec 02 '16 at 21:38
  • I think the problem is that your browser waits until it gets all the output before displaying anything. – John Gordon Dec 02 '16 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. –  Dec 02 '16 at 21:54
  • Maybe try displaying different elements? i.e. use `

    ` instead of `

    `.
    – John Gordon Dec 02 '16 at 22:05
  • Tried with

    and tried without any tags also, none worked.

    –  Dec 02 '16 at 22:22
  • I don't know what else to suggest. You may have to use a formal method like https://en.wikipedia.org/wiki/Push_technology . – John Gordon Dec 02 '16 at 23:34
  • I ran the same script on windows after configuring wampserver, it worked perfectly fine. Wampserver has httpd.conf file which is to be modified. Is there any particular config to be done in apache for linux to make it work? –  Dec 07 '16 at 19:51

1 Answers1

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>
MD Mushfirat Mohaimin
  • 1,966
  • 3
  • 10
  • 22
A. Pace
  • 45
  • 1
  • 8