ShaunG ShaunG - 1 year ago 115
Python Question

Python script only outputs to browser after execution

I have a script which works as expected from the command line, but when I run through a browser it gives output only after the whole script has finished executing. I'm brand new to Python and I can't work out how to modify the behavior to print when it should. Example...

print("Show this")
time.sleep(10)
print("Then this")
time.sleep(10)
print("And then this")


In a browser it'll wait 20 seconds and then display the whole output in one go.

Thanks

Answer Source

Python buffers stdout. So what you probably need to do is flush it.

from sys import stdout

print("Show this")
stdout.flush()
time.sleep(10)
print("Then this")
stdout.flush()
time.sleep(10)
print("And then this")
stdout.flush()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download