简体   繁体   English

Python等待打印不完整的行?

[英]Python waits to print incomplete lines?

Take this Python 3 code snippet: 遵循以下Python 3代码段:

print("walrus")
timeConsumingTask()
print("giraffe")

When run, it prints walrus and, after a delay, giraffe (each on their own lines). 运行时,它将打印walrus并在延迟后打印giraffe (每个都在自己的行上)。

Now take this similar snippet: 现在,使用以下类似代码段:

print("walrus", end=' ')
timeConsumingTask()
print("giraffe", end=' ')

After a delay, it prints walrus giraffe at the same time — although I would expect the first word to print first, and then the second, with a delay in between. 延迟后,它会同时打印walrus giraffe -尽管我希望第一个单词先打印,然后再打印第二个单词,中间会有一个延迟。

Why is this happening? 为什么会这样呢? And is there anyway of fixing this (besides not using end )? 并且有解决此问题的方法(除了不使用end之外)?

I am using Python 3.4.2. 我正在使用Python 3.4.2。

This is due to Python (well, generally your system's C stdio library) buffering the output. 这是由于Python(通常是系统的C stdio库)缓冲了输出。 In general this is desirable because it leads to better performance, but as you've noticed, sometimes it's not what you want. 通常,这是可取的,因为它可以带来更好的性能,但是正如您所注意到的,有时并不是您想要的。

Depending on what you want to achieve, there are a number of ways round this: 根据您要实现的目标,有多种方法可以解决此问题:

  • Print to stderr instead of stdout ( stderr is not buffered by default): 打印到stderr而不是stdout (默认情况下不缓存stderr ):

     print("walrus", end=" ", file=sys.stderr) 
  • Flush after printing: 打印后冲洗:

     print("walrus", end=" ") sys.stdout.flush() 

    or, more compactly (for Python >3.3), 或者,更紧凑(对于Python> 3.3),

     print("walrus", end=" ", flush=True) 
  • There are also some options in the answers to this question , though not all are applicable to Python 3. 这个问题的答案中也有一些选项,尽管并非所有选项都适用于Python 3。

Standard output is line-buffered by default; 默认情况下,标准输出是行缓冲的; incomplete lines are held in the buffer until a newline character is written (or the buffer fills up). 不完整的行将保留在缓冲区中,直到写入换行符(或缓冲区填满)为止。 You can force the text to be written by flushing the buffer with 您可以通过使用以下命令刷新缓冲区来强制写入文本

print("walrus", end=' ')
sys.stdout.flush()
timeConsumingTask()
print("giraffe", end=' ')

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

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