Correcting out of order printing from stream redirection

送分小仙女□ 提交于 2019-12-04 18:44:51
Lack

The output to stdout is buffered: that is, print statements actually write to a buffer, and this buffer is only occassionally flushed to the terminal. Each process has a separate buffer, which is why writes from different processes can appear out of order (This is a common problem, as in Why subprocess stdout to a file is written out of order?)

In this case, the output is in order, but appears out of order when it is redirected. Why? This article explains:

  • stdin is always buffered
  • stderr is always unbuffered
  • if stdout is a terminal then buffering is automatically set to line buffered, else it is set to buffered

So, when output was going to a terminal, it was flushing every line, and happened to appear in order. When redirecting, a long buffer is used (typically 4096 bytes). Since you printed less than that, whichever subprocess finished first was flushed first.

The solution is to use flush(), or entirely disable buffering for the process (see Disable output buffering)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!