From cb70fb3bfbb011aa8030ba076db4c12da562d06a Mon Sep 17 00:00:00 2001 From: Julio Biason Date: Wed, 10 Aug 2022 15:40:48 -0300 Subject: [PATCH] Playing with file descriptors --- tee.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 tee.py diff --git a/tee.py b/tee.py new file mode 100644 index 0000000..9b0284f --- /dev/null +++ b/tee.py @@ -0,0 +1,36 @@ +"""Experimental file-like object that captures output but still send content to +a real file.""" + +import io +import subprocess + + +class Tee(io.FileIO): + def close(self): + print('TeeClose') + return super().close() + + def readline(self, size): + print('TeeReadLine') + super().readline(size) + + def readlines(self, hint): + print('TeeReadLines') + super().readlines(size) + + def writelines(self, lines): + print('TeeWriteLines') + return super().writelines(lines) + + def write(self, b): + print('TeeWite:', b) + return super().write(b) + + +def main(): + with Tee('tee.txt', 'w') as target: + subprocess.run('ls', stdout=target, check=False) + + +if __name__ == '__main__': + main()