简体   繁体   中英

Python waits to print incomplete lines?

Take this Python 3 code snippet:

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

When run, it prints walrus and, after a delay, giraffe (each on their own lines).

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.

Why is this happening? And is there anyway of fixing this (besides not using end )?

I am using Python 3.4.2.

This is due to Python (well, generally your system's C stdio library) buffering the output. 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):

     print("walrus", end=" ", file=sys.stderr) 
  • Flush after printing:

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

    or, more compactly (for 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.

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=' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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