Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable output buffering

Is output buffering enabled by default in Python's interpreter for sys.stdout?

If the answer is positive, what are all the ways to disable it?

Suggestions so far:

  1. Use the -u command line switch
  2. Wrap sys.stdout in an object that flushes after every write
  3. Set PYTHONUNBUFFERED env var
  4. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Is there any other way to set some global flag in sys/sys.stdout programmatically during execution?

like image 215
Eli Bendersky Avatar asked Sep 20 '08 09:09

Eli Bendersky


People also ask

What are output buffers?

An output buffer is a location in memory or cache where data ready to be seen is held until the display device is ready. Buffer, Memory terms, Output.

What is output buffering in Python?

Summary: Python output buffering is the process of storing the output of your code in buffer memory. Once the buffer is full, the output gets displayed on the standard output screen.

What is output buffering in PHP INI?

Output buffering is a mechanism for controlling how much output data (excluding headers and cookies) PHP should keep internally before pushing that data to the client. If your application's output exceeds this setting, PHP will send that data in chunks of roughly the size you specify.


2 Answers

From Magnus Lycka answer on a mailing list:

You can skip buffering for a whole python process using "python -u" (or#!/usr/bin/env python -u etc) or by setting the environment variable PYTHONUNBUFFERED.

You could also replace sys.stdout with some other stream like wrapper which does a flush after every call.

class Unbuffered(object):    def __init__(self, stream):        self.stream = stream    def write(self, data):        self.stream.write(data)        self.stream.flush()    def writelines(self, datas):        self.stream.writelines(datas)        self.stream.flush()    def __getattr__(self, attr):        return getattr(self.stream, attr)  import sys sys.stdout = Unbuffered(sys.stdout) print 'Hello' 
like image 65
Seb Avatar answered Sep 23 '22 18:09

Seb


I would rather put my answer in How to flush output of print function? or in Python's print function that flushes the buffer when it's called?, but since they were marked as duplicates of this one (what I do not agree), I'll answer it here.

Since Python 3.3, print() supports the keyword argument "flush" (see documentation):

print('Hello World!', flush=True) 
like image 35
Cristóvão D. Sousa Avatar answered Sep 22 '22 18:09

Cristóvão D. Sousa