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 unbuffe
Why not try using an unbuffered file?
f = open('xyz.log', 'a', 0)
OR
sys.stdout = open('out.log', 'a', 0)
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.
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...')
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)
self.fd.flush()
return ret
def writelines(self, lines):
ret = self.writelines(lines)
self.fd.flush()
return ret
def flush(self):
return self.fd.flush
def close(self):
return self.fd.close()
def fileno(self):
return self.fd.fileno()
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
I first struggled to understand how the flush option was working. I wanted to do a 'loading display' and here is the solution I found:
for i in range(100000):
print('{:s}\r'.format(''), end='', flush=True)
print('Loading index: {:d}/100000'.format(i+1), end='')
The first line flushes the previous print and the second line prints a new updated message. I don't know if an one-line syntax exists here.