diff --git a/python/ipywidgets/ipywidgets/widgets/tests/test_widget_output.py b/python/ipywidgets/ipywidgets/widgets/tests/test_widget_output.py index 9afcc7916e..ae960eade8 100644 --- a/python/ipywidgets/ipywidgets/widgets/tests/test_widget_output.py +++ b/python/ipywidgets/ipywidgets/widgets/tests/test_widget_output.py @@ -237,3 +237,16 @@ def test_append_display_data(): }, ) assert widget.outputs == expected1 or widget.outputs == expected2 + + +def test_kernel_side_output(): + output = widget_output.Output() + with output: + print("snakes!") + assert output.outputs == ( + { + 'output_type': 'stream', + 'name': 'stdout', + 'text': 'snakes! + } + ) diff --git a/python/ipywidgets/ipywidgets/widgets/widget_output.py b/python/ipywidgets/ipywidgets/widgets/widget_output.py index 150ac93471..60bfda73d6 100644 --- a/python/ipywidgets/ipywidgets/widgets/widget_output.py +++ b/python/ipywidgets/ipywidgets/widgets/widget_output.py @@ -62,6 +62,10 @@ def func(): __counter = 0 + def __init__(self, *args, **kwargs): + super(Output, self).__init__(*args, **kwargs) + self._hooks = [] + def clear_output(self, *pargs, **kwargs): """ Clear the content of the output widget. @@ -108,6 +112,17 @@ def __enter__(self): """Called upon entering output widget context manager.""" self._flush() ip = get_ipython() + if hasattr(ip.display_pub, "register_hook") and hasattr(sys.stdout, "register_hook"): + def hook(msg): + if msg["msg_type"] == "display_data": + self.outputs += ({"output_type": "display_data", "data": msg["content"]["data"], "metadata": msg["content"]["metadata"]},) + return None + return msg + ip.display_pub.register_hook(hook) + sys.stdout.register_hook(hook) + self._hooks.append(hook) + return + kernel = None if ip and getattr(ip, "kernel", None) is not None: kernel = ip.kernel @@ -147,6 +162,12 @@ def __exit__(self, etype, evalue, tb): u'ename': etype.__name__ }) self._flush() + if self._hooks: + ip = get_ipython() + hook = self._hooks.pop() + ip.display_pub.unregister_hook(hook) + sys.stdout.unregister_hook(hook) + return self.__counter -= 1 if self.__counter == 0: self.msg_id = ''