Python:-u选项的意义是什么?

69

我注意到在一些Python代码中使用了参数-u来启动Python解释器。我查看了Python的man手册,但是没有找到太多有用的信息。请给我一些示例。


4
当我从另一个进程或批处理中启动Python并且想要连续监视输出而不是大块输出时,我发现这非常有用。请参考https://dev59.com/inVD5IYBdhLWcg3wDHDm。 - Charles Beattie
2个回答

75

来自python --help

-u     : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'
该手册页面指出:
-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.
Python以带缓冲区的方式打开标准输入、输出和错误流,会将数据读取或写入到内存中,直到达到阈值。选项-u可以禁用这些缓冲区。
此外,Python还能够解释打开文件中的换行符,并将其从和转换为本地平台的换行符(文本模式)。使用-u选项可以禁用这种转换,使你能够处理二进制数据,而不必担心可能发生的\r\n组合问题。这相当于在使用open()函数打开文件时使用rbwb模式。

无缓冲二进制标准输出和标准错误流;?? - Shraddha
对于Python3.4,无论如何使用'-u',stdin始终是带缓冲的。(来自python3.4 --help) - Jonathan Hartley
@JonathanHartley:这里手册可能是错误的;请注意Python 2.7中的--help信息也没有提到stdin。这是因为stdin缓冲区不受Python控制。 - Martijn Pieters
@JonathanHartley:Python 3手册也取消了stdin。请参阅关闭管道中的缓冲以了解使stdin无缓冲的方法。 - Martijn Pieters

28

Python适用于读取和输出大量数据。其中一种优化是Python解释器的标准输入和输出缓冲。这意味着每当程序尝试使用其中一个流时,解释器会将使用情况分成大块并一次性发送这些块。这比单独发送每个读/写操作要快,但明显缺点是数据可能会在中间被阻塞。

-u标志关闭此行为。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接