I am trying to improve the read and write functionality. The task is to have console working while I receive outputs from commands I have send. The issue is I do not know when the response ended e.g. ping local host posts line, after line and somewhen stops, but when working with more commands its unpredictable for me.
The methods I have googled is marking the end marked with some text and dynamic time measuring, but adding echo on the top of every commands sometimes not work properly (some commands does not like having echo after them). My time measuring implementation is clunky too.
TLDR: I need to improve capturing the end of data transmission and I dont know how.
The current code is:
def send_command(self, command, timeout=1):
read_output = []
self.return_code = 0
self.process.stdin.write(command.encode() + b'n')
self.process.stdin.write(b'echo "EOF"n')
self.process.stdin.flush()
output = self.process.stdout.readline().strip().decode()
while output != 'EOF':
start_time = time.time()
read_output.append(output)
output = self.process.stdout.readline().strip().decode()
end_time = time.time()
if (end_time - start_time) > timeout:
self.return_code = 1
return read_output
I tried googled solutions, implemented them and the result is as above. It would be lovely to have any tip how to improve what I already achieved.