channels.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """A kernel client for in-process kernels."""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from jupyter_client.channelsabc import HBChannelABC
  5. from .socket import DummySocket
  6. #-----------------------------------------------------------------------------
  7. # Channel classes
  8. #-----------------------------------------------------------------------------
  9. class InProcessChannel(object):
  10. """Base class for in-process channels."""
  11. proxy_methods = []
  12. def __init__(self, client=None):
  13. super(InProcessChannel, self).__init__()
  14. self.client = client
  15. self._is_alive = False
  16. def is_alive(self):
  17. return self._is_alive
  18. def start(self):
  19. self._is_alive = True
  20. def stop(self):
  21. self._is_alive = False
  22. def call_handlers(self, msg):
  23. """ This method is called in the main thread when a message arrives.
  24. Subclasses should override this method to handle incoming messages.
  25. """
  26. raise NotImplementedError('call_handlers must be defined in a subclass.')
  27. def flush(self, timeout=1.0):
  28. pass
  29. def call_handlers_later(self, *args, **kwds):
  30. """ Call the message handlers later.
  31. The default implementation just calls the handlers immediately, but this
  32. method exists so that GUI toolkits can defer calling the handlers until
  33. after the event loop has run, as expected by GUI frontends.
  34. """
  35. self.call_handlers(*args, **kwds)
  36. def process_events(self):
  37. """ Process any pending GUI events.
  38. This method will be never be called from a frontend without an event
  39. loop (e.g., a terminal frontend).
  40. """
  41. raise NotImplementedError
  42. class InProcessHBChannel(object):
  43. """A dummy heartbeat channel interface for in-process kernels.
  44. Normally we use the heartbeat to check that the kernel process is alive.
  45. When the kernel is in-process, that doesn't make sense, but clients still
  46. expect this interface.
  47. """
  48. time_to_dead = 3.0
  49. def __init__(self, client=None):
  50. super(InProcessHBChannel, self).__init__()
  51. self.client = client
  52. self._is_alive = False
  53. self._pause = True
  54. def is_alive(self):
  55. return self._is_alive
  56. def start(self):
  57. self._is_alive = True
  58. def stop(self):
  59. self._is_alive = False
  60. def pause(self):
  61. self._pause = True
  62. def unpause(self):
  63. self._pause = False
  64. def is_beating(self):
  65. return not self._pause
  66. HBChannelABC.register(InProcessHBChannel)