views:

20434

answers:

5

I would like to force Python's print function to output to the screen.

+56  A: 
import sys
sys.stdout.flush()

print by default prints to sys.stdout

References:

CesarB
+21  A: 

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.

gimel
A: 

Using the -u command-line switch works, but it is a little bit clumsy in my opinion. I usually use a custom stdout, like this:

class flushfile(file):
  def __init__(self, f):
    self.f = f
  def write(self, x)
    self.f.write(x)
    self.f.flush()

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

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

Dan
+2  A: 

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):
        self.f.write(x)
        self.f.flush()

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

print "foo"

The result:

Traceback (most recent call last):
  File "./passpersist.py", 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):

to

class flushfile(object):

makes it work just fine.

Kamil Kisiel
+1  A: 

Why not try using an unbuffered file?

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

OR

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

This solved my problem described here http://stackoverflow.com/questions/1654875/ouput-file-redirection-in-python/1655213#1655213 . Thank you. Great tip.
chmike