You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.6 KiB

4 years ago
  1. """Replacements for sys.displayhook that publish over ZMQ."""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import sys
  5. from IPython.core.displayhook import DisplayHook
  6. from ipykernel.jsonutil import encode_images, json_clean
  7. from ipython_genutils.py3compat import builtin_mod
  8. from traitlets import Instance, Dict, Any
  9. from jupyter_client.session import extract_header, Session
  10. class ZMQDisplayHook(object):
  11. """A simple displayhook that publishes the object's repr over a ZeroMQ
  12. socket."""
  13. topic = b'execute_result'
  14. def __init__(self, session, pub_socket):
  15. self.session = session
  16. self.pub_socket = pub_socket
  17. self.parent_header = {}
  18. def get_execution_count(self):
  19. """This method is replaced in kernelapp"""
  20. return 0
  21. def __call__(self, obj):
  22. if obj is None:
  23. return
  24. builtin_mod._ = obj
  25. sys.stdout.flush()
  26. sys.stderr.flush()
  27. contents = {u'execution_count': self.get_execution_count(),
  28. u'data': {'text/plain': repr(obj)},
  29. u'metadata': {}}
  30. self.session.send(self.pub_socket, u'execute_result', contents,
  31. parent=self.parent_header, ident=self.topic)
  32. def set_parent(self, parent):
  33. self.parent_header = extract_header(parent)
  34. class ZMQShellDisplayHook(DisplayHook):
  35. """A displayhook subclass that publishes data using ZeroMQ. This is intended
  36. to work with an InteractiveShell instance. It sends a dict of different
  37. representations of the object."""
  38. topic=None
  39. session = Instance(Session, allow_none=True)
  40. pub_socket = Any(allow_none=True)
  41. parent_header = Dict({})
  42. def set_parent(self, parent):
  43. """Set the parent for outbound messages."""
  44. self.parent_header = extract_header(parent)
  45. def start_displayhook(self):
  46. self.msg = self.session.msg(u'execute_result', {
  47. 'data': {},
  48. 'metadata': {},
  49. }, parent=self.parent_header)
  50. def write_output_prompt(self):
  51. """Write the output prompt."""
  52. self.msg['content']['execution_count'] = self.prompt_count
  53. def write_format_data(self, format_dict, md_dict=None):
  54. self.msg['content']['data'] = json_clean(encode_images(format_dict))
  55. self.msg['content']['metadata'] = md_dict
  56. def finish_displayhook(self):
  57. """Finish up all displayhook activities."""
  58. sys.stdout.flush()
  59. sys.stderr.flush()
  60. if self.msg['content']['data']:
  61. self.session.send(self.pub_socket, self.msg, ident=self.topic)
  62. self.msg = None