pipe-io-server/pipe_io_server/pipe_reader_thread.py
2018-12-15 00:32:29 +01:00

27 lines
749 B
Python

from threading import Thread
from .terminate_process_on_failure import terminate_process_on_failure
class PipeReaderThread(Thread):
_stop_sequence = b'stop_reading'
def __init__(self, pipe_path, message_handler):
super().__init__()
self._message_handler = message_handler
self._pipe_path = pipe_path
@terminate_process_on_failure
def run(self):
while True:
with open(self._pipe_path, 'rb') as pipe:
message = pipe.read()
if message == self._stop_sequence:
break
self._message_handler(message)
def stop(self):
with open(self._pipe_path, 'wb') as pipe:
pipe.write(self._stop_sequence)
self.join()