From 38c81e0d29128db20d7902b91b7493818fcfa40d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Thu, 9 May 2019 13:46:31 +0200 Subject: [PATCH] Add support for an on_stop callback --- echo_server.py | 1 + pipe_io_server/pipe_io_server.py | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/echo_server.py b/echo_server.py index c87751b..e41c5b2 100644 --- a/echo_server.py +++ b/echo_server.py @@ -12,6 +12,7 @@ if __name__ == "__main__": pipe_io = EchoPipeIOServer('in', 'out') signal(SIGTERM, lambda a, b: pipe_io.stop()) signal(SIGINT, lambda a, b: pipe_io.stop()) + pipe_io.on_stop = lambda: print('Stopping...') pipe_io.start() print('Running pipe IO server with named pipes:') print(f'Input: {pipe_io.in_pipe}') diff --git a/pipe_io_server/pipe_io_server.py b/pipe_io_server/pipe_io_server.py index 6abaa40..2c3e2f0 100644 --- a/pipe_io_server/pipe_io_server.py +++ b/pipe_io_server/pipe_io_server.py @@ -1,5 +1,6 @@ from abc import ABC, abstractmethod from threading import Thread, Event +from typing import Callable from .pipe_reader_thread import PipeReaderThread from .pipe_writer_thread import PipeWriterThread @@ -15,6 +16,7 @@ class PipeIOServer(ABC, Thread): self._stop_event = Event() self._reader_thread, self._writer_thread = self._create_io_threads() self._io_threads = (self._reader_thread, self._writer_thread) + self._on_stop = lambda: None def _create_pipes(self, permissions): Pipe(self.in_pipe).recreate(permissions) @@ -58,6 +60,14 @@ class PipeIOServer(ABC, Thread): thread.stop() Pipe(self.in_pipe).remove() Pipe(self.out_pipe).remove() + self._on_stop() + + def _set_on_stop(self, value): + if not isinstance(value, Callable): + raise ValueError("Supplied object is not callable!") + self._on_stop = value + + on_stop = property(fset=_set_on_stop) def wait(self): self._stop_event.wait()