File: mergeall-products/unzipped/autoflush.py (original) (raw)

"""

autoflush.py (part of Mergeall [3.1])

Force print()'s text to be unbuffered (i.e., flushed at each line end), by resetting the standard streams it uses in the sys module to a proxy object.

This module is used by scripts that wish to make output unbuffered when run as frozen executables, where Python's "-u" and PYTHONUNBUFFERED may not be available (e.g., Mac apps). diffall and cpall both use this code for "-u".

Alternatives: some freeze systems/versions may support Python switches or always flush prints automatically, and the print() builtin may be reset to a custom version at startup (as done in mergeall.py: see its code).

"""

import sys

class AutoFlush: """ Stream proxy: flush lines as they are written. TBD: autoflush if text contains an endline too? """ def init(self, stream): self.stream = stream

def write(self, data):
    res = self.stream.write(data)
    if data.endswith('\n'):
        self.stream.flush()
    return res

def __getattr__(self, attr):
    # and everything else
    return getattr(self.stream, attr)

def setFlushedOuput(): """ Reset streams to proxies globally. print() uses sys.stdout internally. """ sys.stdout = AutoFlush(sys.stdout) sys.stderr = AutoFlush(sys.stderr)