Skip to content

Instantly share code, notes, and snippets.

@prophile
Created April 11, 2016 09:26
Show Gist options
  • Save prophile/81cfff021d89ffb894fd40336dfc5eec to your computer and use it in GitHub Desktop.
Save prophile/81cfff021d89ffb894fd40336dfc5eec to your computer and use it in GitHub Desktop.
class TraceIO(object):
def __init__(self, stream, log=print):
self.stream = stream
self.log = log
def __enter__(self):
return self.stream.__enter__()
def __exit__(self, *args):
return self.stream.__exit__(*args)
def fileno(self):
return self.stream.fileno()
@property
def closed(self):
return self.stream.closed
def close(self):
self.log("close")
self.stream.close()
def flush(self):
self.log("flush")
self.stream.flush()
def isatty(self):
return self.stream.isatty()
def readable(self):
return self.stream.readable()
def readline(self, size=-1):
self.log("readline")
return self.stream.readline(size)
def readlines(self, hint=-1):
self.log("readlines")
return self.stream.readlines(hint)
def seek(self, offset, whence=0):
whence_term = {
0: 'set',
1: 'cur',
2: 'end',
}[whence]
self.log("seek", offset, whence_term)
return self.stream.seek(offset, whence)
def seekable(self):
return self.stream.seekable()
def tell(self):
return self.stream.tell()
def truncate(self, size=None):
self.log("truncate", repr(size))
return self.stream.truncate(size)
def writable(self):
return self.stream.writable()
def writelines(self, lines):
for line in lines:
self.write(line)
def read(self, size=-1):
if size == -1:
return self.readall()
self.log("read", size)
return self.stream.read(size)
def readall(self):
self.log("readall")
return self.stream.read(-1)
def readinto(self, b):
self.log("readinto", len(b))
return self.stream.readinto(b)
def write(self, b):
self.log("write", len(b))
return self.stream.write(b)
def __iter__(self):
while True:
line = self.readline()
if not line:
break
yield line
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment