Extending io.BufferedWriter breaks flush method (python)

58 Views Asked by At

Python's open method returns an io.BufferedWriter Class, which I extended with the following class:

class BufferedWriterSplitter(io.BufferedWriter):

    def __init__(self, writer, listenerOnly = False):
        if not listenerOnly:
            super().__init__(writer)
        self.listener = None
        self.buffer = ""
    
    def register_listener(self, listener):
        self.listener = listener

    def write(self, b):
        

        if self.buffer: 
            b = self.buffer + b.decode()
        else:
            b = b.decode()
        self.buffer = ""
            
        super().write(b.encode())
            

    def flush(self):
        super().flush()

The purpose of this class is to allow me to split the stream that gets written to the file in two, allowing me to analyze what is written separately - like this:

loggingHandle = BufferedWriterSplitter(open(raw_log_file_path, "ab"))
loggingHandle.register_listener(self.listener) #the analysis
sshHandle.logfile_read = loggingHandle

the sshHandle is a pexpect.spawn child object, the methods for which can be found here, particularly line 127 which deals with the logging handle

The expected behavior is that the log file raw_log_file should be written to immediately every time data is received across the ssh connection. Instead, the file is only written to when the ssh connection closes, and the whole buffer is written to

By contrast, if I remove the extended class as below, the file is written to continuously, as expected

sshHandle.logfile_read = open(raw_log_file_path, "ab")
0

There are 0 best solutions below