From 343c6d39f9bd2ef019a4759ce187bef9f4e30e49 2016-09-18 20:52:41 From: Matthias Bussonnier Date: 2016-09-18 20:52:41 Subject: [PATCH] Backport PR #9851: Also capture execution results using sys.displayhook From discussion on mailing list. It's not clear if this is what we want to do, or if it should be controlled by a separate option, but it's submitted for consideration. --- diff --git a/IPython/core/displayhook.py b/IPython/core/displayhook.py index 07d733e..d6d108d 100644 --- a/IPython/core/displayhook.py +++ b/IPython/core/displayhook.py @@ -293,3 +293,17 @@ class DisplayHook(Configurable): # IronPython blocks here forever if sys.platform != "cli": gc.collect() + + +class CapturingDisplayHook(object): + def __init__(self, shell, outputs=None): + self.shell = shell + if outputs is None: + outputs = [] + self.outputs = outputs + + def __call__(self, result=None): + if result is None: + return + format_dict, md_dict = self.shell.display_formatter.format(result) + self.outputs.append((format_dict, md_dict)) diff --git a/IPython/utils/capture.py b/IPython/utils/capture.py index 1731bf2..d129c03 100644 --- a/IPython/utils/capture.py +++ b/IPython/utils/capture.py @@ -137,6 +137,7 @@ class capture_output(object): def __enter__(self): from IPython.core.getipython import get_ipython from IPython.core.displaypub import CapturingDisplayPublisher + from IPython.core.displayhook import CapturingDisplayHook self.sys_stdout = sys.stdout self.sys_stderr = sys.stderr @@ -156,7 +157,9 @@ class capture_output(object): self.save_display_pub = self.shell.display_pub self.shell.display_pub = CapturingDisplayPublisher() outputs = self.shell.display_pub.outputs - + self.save_display_hook = sys.displayhook + sys.displayhook = CapturingDisplayHook(shell=self.shell, + outputs=outputs) return CapturedIO(stdout, stderr, outputs) @@ -165,5 +168,6 @@ class capture_output(object): sys.stderr = self.sys_stderr if self.display and self.shell: self.shell.display_pub = self.save_display_pub + sys.displayhook = self.save_display_hook diff --git a/docs/source/whatsnew/pr/capture-displayhook.rst b/docs/source/whatsnew/pr/capture-displayhook.rst new file mode 100644 index 0000000..5952f3c --- /dev/null +++ b/docs/source/whatsnew/pr/capture-displayhook.rst @@ -0,0 +1,3 @@ +- The :cellmagic:`capture` magic can now capture the result of a cell (from an + expression on the last line), as well as printed and displayed output. + :ghpull:`9851`.