I want to make a wrapper around an existing program to create a programmable interface. The idea is that I want to expose functions that will send the appropriate input to the subprocess, and return a value corresponding to the input of that process.
However, I don't know how to make my interface wait for the program to return something.
This is what I've done.
class ProcessWrapper:
def __init__(self, process):
self.proc = process
def communicate(self, message):
self.proc.stdin.write(message)
while True:
result = self.proc.stdout.readlines()
if result: return result
But this seems very ressource-demanding. Is there a better way?
readlines
is a non-blocking function, meaning the loop will execute as fast as possible, instead of waiting for some output from the process.
What should be used here instead is readline
, essentially the same function but blocking.
def communicate(self, message):
self.proc.stdin.send(message)
return self.proc.stdout.readline()