简体   繁体   English

-u标志对Python脚本的性能或执行有何作用?

[英]What does the -u flag do to performance or execution of a Python script?

A multiprocessing.Process powered script I was writing was not printing to the terminal as expected, so instead of adding flush=True to every single print function, I added the -u flag to my python command line. 我正在编写的由multiprocessing.Process驱动的脚本未能按预期方式打印到终端,因此,我没有在每个单独的打印函数中添加flush=True ,而是在Python命令行中添加了-u标志。

So instead of this: 所以代替这个:

python /path/to/script

I ran: 我跑了:

python -u /path/to/script

And voila! 瞧! The myriad print functions all printed as expected. 无数的打印功能均按预期打印。

What else does running a Python script unbuffered do besides making the print function work as expected? 除了使打印功能按预期工作之外,无缓冲地运行Python脚本还有什么作用? (is my main question...) (是我的主要问题...)

And why isn't it unbuffered in the first place? 而且为什么它不是一开始就没有缓冲?

Thank you! 谢谢!

Buffering improves performance when large amounts of output are being generated incrementally but don't need to be processed in real time. 当逐渐生成大量输出但不需要实时处理时,缓冲可提高性能。

For instance, if you are downloading data from a remote server and writing it to a file or the console, and all you really care is the end result (the complete file or the full output), then it's reasonable to not output a few bytes at a time to the file, but instead wait for a large chunk of bytes to be received and then write them all at once - less time spent in write function calls, and (if writing to disk) fewer disk seeks and more long continuous writes. 例如,如果您要从远程服务器下载数据并将其写入文件或控制台,而您真正关心的只是最终结果(完整文件或完整输出),那么合理的做法是不输出一些字节一次写入文件,而是等待接收大量字节,然后一次写入所有字节-更少的写入函数调用时间,并且(如果写入磁盘)更少的磁盘搜寻和更长的连续写入。

Normally, invocations of Python will flush their output when the python process exits and/or when the buffer is full. 通常,当python进程退出和/或缓冲区已满时,Python的调用将刷新其输出。 Chances are whatever you were doing either wasn't terminating gracefully or wasn't generating enough output to fill up the buffer, and therefore the normal conditions for flushing the buffer weren't being triggered. 可能是您正在执行的操作要么没有正常终止,要么没有生成足够的输出来填充缓冲区,因此未触发刷新缓冲区的正常条件。

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

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