from threading import Thread from queue import Queue class PipeWriterThread(Thread): def __init__(self, pipe_path): super().__init__() self._pipe_path = pipe_path self._write_queue = Queue() def write(self, message): self._write_queue.put(message, block=True) def run(self): while True: message = self._write_queue.get(block=True) if message is None: break with open(self._pipe_path, 'wb') as pipe: pipe.write(message) def stop(self): self._write_queue.put(None) self.join()