From d12c9807f53d2b6948b7d7ec061c0aa8268a31b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Fri, 12 Apr 2019 15:42:00 +0200 Subject: [PATCH] Implement Python bindings for pipe io client --- clients/python/example.py | 7 ++++ clients/python/pipe_io.py | 69 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 clients/python/example.py create mode 100644 clients/python/pipe_io.py diff --git a/clients/python/example.py b/clients/python/example.py new file mode 100644 index 0000000..fff7cc8 --- /dev/null +++ b/clients/python/example.py @@ -0,0 +1,7 @@ +from pipe_io import PipeIO + + +if __name__ == '__main__': + with PipeIO('in', 'out') as pipeio: + pipeio.reader.message_handler = pipeio.writer.send_message + pipeio.reader.run() diff --git a/clients/python/pipe_io.py b/clients/python/pipe_io.py new file mode 100644 index 0000000..cac23b4 --- /dev/null +++ b/clients/python/pipe_io.py @@ -0,0 +1,69 @@ +from typing import Callable + + +class PipeReader: + def __init__(self, pipe_path): + self._pipe = open(pipe_path, 'rb') + self._message_handler = lambda msg: None + + def __enter__(self): + return self + + def __exit__(self, type_, value, traceback): + self.close() + + def close(self): + self._pipe.close() + + @property + def message_handler(self): + return self._message_handler + + @message_handler.setter + def message_handler(self, value): + if not isinstance(value, Callable): + raise ValueError("message_handler must be callable!") + self._message_handler = value + + def run(self): + msg = self.recv_message() + while msg: + self._message_handler(msg) + msg = self.recv_message() + + def recv_message(self): + return self._pipe.readline()[:-1] + + +class PipeWriter: + def __init__(self, pipe_path): + self._pipe = open(pipe_path, 'wb') + + def __enter__(self): + return self + + def __exit__(self, type_, value, traceback): + self.close() + + def close(self): + self._pipe.close() + + def send_message(self, message): + self._pipe.write(message + b'\n') + self._pipe.flush() + + +class PipeIO: + def __init__(self, in_pipe_path, out_pipe_path): + self.reader = PipeReader(in_pipe_path) + self.writer = PipeWriter(out_pipe_path) + + def __enter__(self): + return self + + def __exit__(self, type_, value, traceback): + self.close() + + def close(self): + self.reader.close() + self.writer.close()