How to Print in Python 2.7 without newline without buffering

Question:

I have a need in Python 2.7 to print text to the console without newline characters, so I can continue writing more text on that same line later with future code. My current implementation involves importing the Python 3 print function from the future library, and using end=”.

This is not ideal as if I print a line, such as:

print("We're doing something...",end='')

And then follow that with any other code, and then a line such as:

print("we finished doing that thing.")

The line gets printed, but it’s all printed at once, meaning that it is buffered until it gets the print with the newline character in it. I would much prefer to be able to output the first print string to the console, execute other code, and then put in the part with the newline. I can’t find anyway to do this with print in Python 2.7. Maybe someone can point me to a functional way to do this? Thanks.

For those suggesting the environment buffering fixes it, it does not. It affects file output and some other miscellaneous things that have nothig to do with it. There is an answer below that is functional overall.

Asked By: Will

||

Answers:

Include this at the beginning of your file:

from __future__ import print_function

Then you can use both end and flush named parameters as if you were on Python 3. It seens you are missing the flush parameter:

print("We're doing something...",end='', flush=True)

If you can’t or would not like to do that for some reason, you should end your legacy print statement with a sole comma. If you need the partial line to be printed, then you have to manually call sys.stdout.flush() soon after printing:

 print "We're doing something...",
 sys.stdout.flush()
 ...
 print "Done!"
Answered By: jsbueno
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.