By Walter Nissen

2008-10-23 17:59:39 8 Comments

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.


@Dan Lenski 2008-10-23 19:54:26

Using the -u command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the -u option. I usually use a custom stdout, like this:

class flushfile:
  def __init__(self, f):
    self.f = f

  def write(self, x):

import sys
sys.stdout = flushfile(sys.stdout)

... Now all your print calls (which use sys.stdout implicitly), will be automatically flushed.

@diedthreetimes 2013-06-23 19:21:43

I recommend not inheriting from file and then delegating to stdout by adding. def __getattr__(self,name): return object.__getattribute__(self.f, name)

@dangonfast 2015-04-27 22:43:11

Without the changes suggested by the comment by @diedthreetimes, I get "ValueError: I/O operation on closed file"

@CesarB 2008-10-23 18:04:59

import sys

print by default prints to sys.stdout.


Python 2

Python 3

@Eugene Sajine 2014-04-17 20:18:03

Since python 3.3. there is an alternaive approach - print has argument to flush now.

@Deep LF 2019-06-20 05:45:05

For python3, you can add directly arguments into print function for flushing output -> print("OK", flush= True)

@Noah Krasser 2015-10-21 17:23:32

With Python 3.x the print() function has been extended:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

So, you can just do:

print("Visiting toilet", flush=True)

Python Docs Entry

@Aaron Hall 2016-02-17 21:01:03

How to flush output of Python print?

I suggest five ways of doing this:

  • In Python 3, call print(..., flush=True) (the flush argument is not available in Python 2's print function, and there is no analogue for the print statement).
  • Call file.flush() on the output file (we can wrap python 2's print function to do this), for example, sys.stdout
  • apply this to every print function call in the module with a partial function,
    print = partial(print, flush=True) applied to the module global.
  • apply this to the process with a flag (-u) passed to the interpreter command
  • apply this to every python process in your environment with PYTHONUNBUFFERED=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 the print function:

print('foo', flush=True) 

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"):

from __future__ import print_function
import sys

if sys.version_info[:2] < (3, 3):
    old_print = print
    def print(*args, **kwargs):
        flush = kwargs.pop('flush', False)
        old_print(*args, **kwargs)
        if flush:
            file = kwargs.get('file', sys.stdout)
            # Why might file=None? IDK, but it works for print(i, file=None)
            file.flush() if file is not None else sys.stdout.flush()

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:

import sys
print 'delayed output'

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:

import functools
print = functools.partial(print, flush=True)

if you look at our new partial function, at least in Python 3:

>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(<built-in function print>, flush=True)

We can see it works just like normal:

>>> print('foo')

And we can actually override the new default:

>>> print('foo', flush=False)

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.:

def foo():
    printf = functools.partial(print, flush=True)
    printf('print stuff like this')

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.

$ python -u


$ python -um package.module

From the docs:

Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.

Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.

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:


If this is set to a non-empty string it is equivalent to specifying the -u option.


Here's the help on the print function from Python 2.7.12 - note that there is no flush argument:

>>> from __future__ import print_function
>>> help(print)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

@kmario23 2015-06-06 11:10:54

I did it like this in Python 3.4:

'''To write to screen in real-time'''
message = lambda x: print(x, flush=True, end="")
message('I am flushing out now...')

@user263387 2016-05-15 19:13:34

In Python 3 you can overwrite print function with default set to flush = True

def print(*objects, sep=' ', end='\n', file=sys.stdout, flush=True):
    __builtins__.print(*objects, sep=sep, end=end, file=file, flush=flush)

@Semicolons and Duct Tape 2016-05-15 19:18:11

this answer seems a little light given all the other high quality responses. you may want to add a little more to it.

@guettli 2011-05-19 08:20:36

Here is my version, which provides writelines() and fileno(), too:

class FlushFile(object):
    def __init__(self, fd):
        self.fd = fd

    def write(self, x):
        ret = self.fd.write(x)
        return ret

    def writelines(self, lines):
        ret = self.writelines(lines)
        return ret

    def flush(self):
        return self.fd.flush

    def close(self):
        return self.fd.close()

    def fileno(self):
        return self.fd.fileno()

@Colin D Bennett 2014-09-22 20:58:27

Superior solution. And it works. Tested on Python 3.4.0. With the other versions, which derive from file, I get an error. There is no file class.

@Eugene Sajine 2014-04-17 20:10:31

Since Python 3.3, you can force the normal print() function to flush without the need to use sys.stdout.flush(); just set the "flush" keyword argument to true. From the documentation:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Print objects to the stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

@Frank 2009-04-12 10:57:58

Why not try using an unbuffered file?

f = open('xyz.log', 'a', 0)


sys.stdout = open('out.log', 'a', 0)

@dangonfast 2015-04-28 12:58:14

He does not want ot create an unbuffered file; he wants to make the existing stdout (redirected to the console, the terminal or whatever: this must not be changed) unbuffered.

@Antony Hatchkins 2012-02-27 08:38:27

Also as suggested in this blog one can reopen sys.stdout in unbuffered mode:

sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Each stdout.write and print operation will be automatically flushed afterwards.

@drevicko 2015-07-01 04:58:11

On Ubuntu 12.04 in python 2.7 this gives me UnsupportedOperation: IOStream has no fileno.

@EKons 2016-04-30 17:43:39

Whoops, Python 3 found out. It won't let me execute this piece of code!

@Don Hatch 2018-10-19 13:41:06

I'm confused by this idiom. After you do this, aren't there now two File-like objects (the original sys.stdout and the new sys.stdout) that both think they "own" the fileno? That's bad, right?

@Kamil Kisiel 2008-11-13 22:15:25

Dan's idea doesn't quite work:

#!/usr/bin/env python
class flushfile(file):
    def __init__(self, f):
        self.f = f
    def write(self, x):

import sys
sys.stdout = flushfile(sys.stdout)

print "foo"

The result:

Traceback (most recent call last):
  File "./", line 12, in <module>
    print "foo"
ValueError: I/O operation on closed file

I believe the problem is that it inherits from the file class, which actually isn't necessary. According to the docs for sys.stdout:

stdout and stderr needn’t be built-in file objects: any object is acceptable as long as it has a write() method that takes a string argument.

so changing

class flushfile(file):


class flushfile(object):

makes it work just fine.

@gecco 2013-01-15 15:30:14

No vote because this IS @Dan's solution... (You should rather comment Dan's post instead of copying his solution)

@gimel 2008-10-23 18:06:49

Running python -h, I see a command line option:

-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'

Here is the relevant doc.

Related Questions

Sponsored Content

1 Answered Questions

[SOLVED] How to pivot a dataframe

8 Answered Questions

[SOLVED] How to redirect the output of print to a TXT file

2 Answered Questions

[SOLVED] What exactly constitutes an "output"?

  • 2019-03-12 19:11:13
  • Adrio Alimin
  • 73 View
  • 2 Score
  • 2 Answer
  • Tags:   python python-idle

4 Answered Questions

[SOLVED] Is it possible to "hack" Python's print function?

0 Answered Questions

In Python3, how do I get the output of "help()" function in to a variable?

  • 2018-11-06 06:58:14
  • 58 View
  • 2 Score
  • 0 Answer
  • Tags:   python python-3.x

6 Answered Questions

[SOLVED] Why is printing to stdout so slow? Can it be sped up?

4 Answered Questions

[SOLVED] Python 3 print() function with Farsi/Arabic characters

5 Answered Questions

[SOLVED] Why print statement is not pythonic?

  • 2009-06-27 23:27:50
  • ilya n.
  • 9623 View
  • 34 Score
  • 5 Answer
  • Tags:   python python-3.x

3 Answered Questions

[SOLVED] Java: Printing program output to a physical printer

3 Answered Questions

Sponsored Content