How do I force Python's print function to output to the screen?
This is not a duplicate of Disable output buffering - the linked question is attempting unbuffered output, while this is more general. The top answers in that question are too powerful or involved for this one (they're not good answers for this), and this question can be found on Google by a relative newbie.
I suggest five ways of doing this:
print(..., flush=True)
(the flush argument is not available in Python 2's print function, and there is no analogue for the print statement).file.flush()
on the output file (we can wrap python 2's print function to do this), for example,sys.stdout
print = partial(print, flush=True)
applied to the module global.-u
) passed to the interpreter commandPYTHONUNBUFFERED=TRUE
(and unset the variable to undo this).Python 3.3+
Using Python 3.3 or higher, you can just provide
flush=True
as a keyword argument to theprint
function:Python 2 (or < 3.3)
They did not backport the
flush
argument to Python 2.7 So if you're using Python 2 (or less than 3.3), and want code that's compatible with both 2 and 3, may I suggest the following compatibility code. (Note the__future__
import must be at/very "near the top of your module"):The above compatibility code will cover most uses, but for a much more thorough treatment, see the
six
module.Alternatively, you can just call
file.flush()
after printing, for example, with the print statement in Python 2:Changing the default in one module to
flush=True
You can change the default for the print function by using functools.partial on the global scope of a module:
if you look at our new partial function, at least in Python 3:
We can see it works just like normal:
And we can actually override the new default:
Note again, this only changes the current global scope, because the print name on the current global scope will overshadow the builtin
print
function (or dereference the compatibility function, if using Python 2, in that current global scope).If you want to do this inside a function instead of on a module's global scope, you should give it a different name, e.g.:
If you declare it a global in a function, you're changing it on the module's global namespace, so you should just put it in the global namespace, unless that specific behavior is exactly what you want.
Changing the default for the process
I think the best option here is to use the
-u
flag to get unbuffered output.or
From the docs:
Changing the default for the shell operating environment
You can get this behavior for all python processes in the environment or environments that inherit from the environment if you set the environment variable to a nonempty string:
e.g., in Linux or OSX:
or Windows:
from the docs:
Addendum
Here's the help on the print function from Python 2.7.12 - note that there is no
flush
argument:Here is my version, which provides writelines() and fileno(), too: