2018-12-14 16:36:53 +00:00
|
|
|
from threading import Thread
|
|
|
|
from queue import Queue
|
|
|
|
|
2018-12-14 23:32:29 +00:00
|
|
|
from .terminate_process_on_failure import terminate_process_on_failure
|
|
|
|
|
2018-12-14 16:36:53 +00:00
|
|
|
|
|
|
|
class PipeWriterThread(Thread):
|
2019-03-28 15:25:53 +00:00
|
|
|
def __init__(self, pipe_path, stop_event):
|
2018-12-14 16:36:53 +00:00
|
|
|
super().__init__()
|
|
|
|
self._pipe_path = pipe_path
|
2019-03-28 15:25:53 +00:00
|
|
|
self._stop_event = stop_event
|
2018-12-14 16:36:53 +00:00
|
|
|
self._write_queue = Queue()
|
|
|
|
|
|
|
|
def write(self, message):
|
|
|
|
self._write_queue.put(message, block=True)
|
|
|
|
|
2018-12-14 23:32:29 +00:00
|
|
|
@terminate_process_on_failure
|
2018-12-14 16:36:53 +00:00
|
|
|
def run(self):
|
2019-03-28 15:25:53 +00:00
|
|
|
try:
|
|
|
|
with open(self._pipe_path, 'w') as pipe:
|
|
|
|
while True:
|
|
|
|
message = self._write_queue.get(block=True)
|
|
|
|
if message is None:
|
|
|
|
self._stop_event.set()
|
|
|
|
break
|
|
|
|
pipe.write(f'{message}\n')
|
|
|
|
pipe.flush()
|
|
|
|
except BrokenPipeError:
|
|
|
|
self._stop_event.set()
|
2018-12-14 16:36:53 +00:00
|
|
|
|
|
|
|
def stop(self):
|
2019-03-28 15:25:53 +00:00
|
|
|
self.unblock()
|
2018-12-14 16:36:53 +00:00
|
|
|
self.join()
|
2019-03-28 15:25:53 +00:00
|
|
|
|
|
|
|
def unblock(self):
|
|
|
|
self._write_queue.put(None)
|
|
|
|
open(self._pipe_path, 'r').close()
|