Python:-u选项的意义?

Shr*_*dha 27 python

我在一些python代码中注意到-u用于启动python解释器.我查看了python的手册页,但是我无法从中得到很多.请举个例子.

Mar*_*ers 33

来自python --help:

-u     : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'
Run Code Online (Sandbox Code Playgroud)

联机帮助页指出:

-u     Force  stdin,  stdout and stderr to be totally unbuffered.  On systems where it matters, also put stdin,
       stdout and stderr in binary mode.  Note that there is internal buffering  in  xreadlines(),  readlines()
       and  file-object  iterators  ("for  line in sys.stdin") which is not influenced by this option.  To work
       around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.
Run Code Online (Sandbox Code Playgroud)

Python以缓冲模式打开stdin,-out和-error流; 它将以更大的块读取或写入,将数据保存在内存中,直到达到阈值.-u禁用这些缓冲区.

此外,python可以解释打开文件上的换行符,并将它们转换为本机平台换行符(文本模式).该-u选项禁用此转换,允许您处理二进制数据,而无需担心\r\n组合可能发生的情况.当使用该功能打开文件时,它相当于使用rbwb模式open().


Kat*_*iel 13

Python针对读入和打印大量数据进行了优化.其中一个优化是Python解释器的标准输入和输出被缓冲.这意味着每当程序尝试使用其中一个流时,解释将阻止使用大块,然后一次性发送块.这比单独发送每个读/写更快,但显然缺点是数据可以在中间"停止".

-u标志关闭此行为.