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.
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!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With