为什么无缓冲的 stderr 会比有缓冲的 stdout 输出的还晚?

2019-01-15 13:49:30 +08:00
 OhYee
import sys
sys.stdout.write("stdout1 ")
sys.stderr.write("stderr1 ")
sys.stdout.write("stdout2 ")
sys.stderr.write("stderr2 ")

print()
string = ""
for i in range(10):
    string = string + str(i) + "\n"
print(string)

在使用 python test.py 执行时,应该是有开启缓冲区的,不加上后面的 print 部分,输出顺序是 stderr1 stderr2 stdout1 stdout2

但是为什么加了后面的 print 部分输出变成了

stdout1 stdout2
0
1
2
3
4
5
6
7
8
9

stderr1 stderr2

stderr 不是无缓冲的么,不应该直接就输出出来在最前面么?

2354 次点击
所在节点    问与答
22 条回复
swulling
2019-01-15 16:01:38 +08:00
@OhYee -u 要看哪个版本,如果是 Python 3 但是是 3.7 以下,那么 -u 也不是 unbuffered,还是 line-buffered
如果是 3.7+,那么
Changed in version 3.7: The text layer of the stdout and stderr streams now is unbuffered.
OhYee
2019-01-15 16:20:28 +08:00
@swulling
感谢,试了下 python3.6.7 没有问题,python3.7.1 存在这个问题
看了下两者的区别,应该就是 unbuffered 导致被截断掉了

此贴完结,感谢几位大佬的帮助

————————————

Python3.6

https://docs.python.org/3.6/using/cmdline.html#cmdoption-u
-u
Force the binary layer of the stdout and stderr streams (which is available as their buffer attribute) to be unbuffered. The text I/O layer will still be line-buffered if writing to the console, or block-buffered if redirected to a non-interactive file.

See also PYTHONUNBUFFERED.

https://docs.python.org/3.6/using/cmdline.html#envvar-PYTHONUNBUFFERED
PYTHONUNBUFFERED
If this is set to a non-empty string it is equivalent to specifying the -u option.



Python3.7

https://docs.python.org/3.7/using/cmdline.html#cmdoption-u
-u
Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream.

See also PYTHONUNBUFFERED.

Changed in version 3.7: The text layer of the stdout and stderr streams now is unbuffered.

https://docs.python.org/3.7/using/cmdline.html#envvar-PYTHONUNBUFFERED
PYTHONUNBUFFERED
If this is set to a non-empty string it is equivalent to specifying the -u option.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/527210

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX