31 lines
870 B
Python
31 lines
870 B
Python
|
from threading import Thread
|
||
|
from os import kill, getpid
|
||
|
from signal import SIGTERM
|
||
|
from traceback import print_exc
|
||
|
|
||
|
|
||
|
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
|
||
|
|
||
|
def run(self):
|
||
|
while True:
|
||
|
with open(self._pipe_path, 'rb') as pipe:
|
||
|
message = pipe.read()
|
||
|
if message == self._stop_sequence:
|
||
|
break
|
||
|
try:
|
||
|
self._message_handler(message)
|
||
|
except: # pylint: disable=bare-except
|
||
|
print_exc()
|
||
|
kill(getpid(), SIGTERM)
|
||
|
|
||
|
def stop(self):
|
||
|
with open(self._pipe_path, 'wb') as pipe:
|
||
|
pipe.write(self._stop_sequence)
|
||
|
self.join()
|