class message(object): """ Generic pretty printer with redirection. It also suports buffering using bufferize() and flush(). """ def __init__(self): self.out = sys.stdout self.buffering = 0 def bufferize(self, f=None): """Activate message's bufferization, can also be used as a decorater.""" if f is not None: @functools.wraps(f) def wrapper(*args, **kwargs): self.bufferize() f(*args, **kwargs) self.flush() return wrapper # If we are still using stdio we need to change it. if not self.buffering: self.out = StringIO() self.buffering += 1 def flush(self): if not self.buffering: raise ValueError( "Tried to flush a message that is not bufferising.") self.buffering -= 1 # We only need to flush if this is the lowest recursion level. if not self.buffering: self.out.flush() sys.stdout.write(self.out.getvalue()) self.out = sys.stdout def __call__(self, text, color=None, attrib=None, teefd=None): if not teefd: teefd = config.Option.get("_teefd") if isinstance(text, six.string_types) and "\x00" not in text: print(colorize(text, color, attrib), file=self.out) if teefd: print(colorize(text, color, attrib), file=teefd) else: pprint.pprint(text, self.out) if teefd: pprint.pprint(text, teefd)
def bufferize(self, f=None): """Activate message's bufferization, can also be used as a decorater.""" if f is not None: @functools.wraps(f) def wrapper(*args, **kwargs): self.bufferize() f(*args, **kwargs) self.flush() return wrapper # If we are still using stdio we need to change it. if not self.buffering: self.out = StringIO() self.buffering += 1