简体   繁体   English

Python脚本仅在执行后输出到浏览器

[英]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. 我是Python的新手,我不知道如何修改行为以在需要时打印。 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. 在浏览器中,它将等待20秒,然后一次性显示整个输出。

Thanks 谢谢

Python buffers stdout . Python缓冲stdout So what you probably need to do is flush it. 因此,您可能需要flush它。

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

Actually it's normal. 其实很正常。

As you are running the script on your computer (via the console for example), the output is sent to the standard output (aka stdout) and your shell is reading directly on stdout. 当您在计算机上运行脚本时(例如,通过控制台),输出将发送到标准输出(aka stdout),并且您的shell将直接在stdout上读取。

When you are running a script from a web server, your browser is expecting a file. 从Web服务器运行脚本时,浏览器需要文件。
Either way, if your web server choose to send you data as soon as it is computed (so you'll get only the first print in your case), or it choose to "bufferize" the output as long as the script has not exited to be able to send you the whole result (the program's output) as a single file. 无论哪种方式,如果您的Web服务器选择在计算后立即将数据发送给您(这样您的情况下只会得到第一份打印结果),或者选择“缓冲”输出,只要脚本没有退出即可。以便将整个结果(程序的输出)作为一个文件发送给您。

In other words, your web server is waiting your program to complete to send you your program's output. 换句话说,您的Web服务器正在等待您的程序完成发送给您程序输出。
As your program has 2 time.sleep(10) , it waits 20sec total + the time of execution (almost negligible) of the print() calls. 由于您的程序有2 time.sleep(10) ,因此总共要等待20秒+ print()调用的执行时间(几乎可以忽略)。

Your question is not python dependent but more like web-related. 您的问题与python无关,而与网络相关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM