##// END OF EJS Templates
Backport PR #9851: Also capture execution results using sys.displayhook...
Matthias Bussonnier -
Show More
@@ -0,0 +1,3 b''
1 - The :cellmagic:`capture` magic can now capture the result of a cell (from an
2 expression on the last line), as well as printed and displayed output.
3 :ghpull:`9851`.
@@ -293,3 +293,17 b' class DisplayHook(Configurable):'
293 # IronPython blocks here forever
293 # IronPython blocks here forever
294 if sys.platform != "cli":
294 if sys.platform != "cli":
295 gc.collect()
295 gc.collect()
296
297
298 class CapturingDisplayHook(object):
299 def __init__(self, shell, outputs=None):
300 self.shell = shell
301 if outputs is None:
302 outputs = []
303 self.outputs = outputs
304
305 def __call__(self, result=None):
306 if result is None:
307 return
308 format_dict, md_dict = self.shell.display_formatter.format(result)
309 self.outputs.append((format_dict, md_dict))
@@ -137,6 +137,7 b' class capture_output(object):'
137 def __enter__(self):
137 def __enter__(self):
138 from IPython.core.getipython import get_ipython
138 from IPython.core.getipython import get_ipython
139 from IPython.core.displaypub import CapturingDisplayPublisher
139 from IPython.core.displaypub import CapturingDisplayPublisher
140 from IPython.core.displayhook import CapturingDisplayHook
140
141
141 self.sys_stdout = sys.stdout
142 self.sys_stdout = sys.stdout
142 self.sys_stderr = sys.stderr
143 self.sys_stderr = sys.stderr
@@ -156,7 +157,9 b' class capture_output(object):'
156 self.save_display_pub = self.shell.display_pub
157 self.save_display_pub = self.shell.display_pub
157 self.shell.display_pub = CapturingDisplayPublisher()
158 self.shell.display_pub = CapturingDisplayPublisher()
158 outputs = self.shell.display_pub.outputs
159 outputs = self.shell.display_pub.outputs
159
160 self.save_display_hook = sys.displayhook
161 sys.displayhook = CapturingDisplayHook(shell=self.shell,
162 outputs=outputs)
160
163
161 return CapturedIO(stdout, stderr, outputs)
164 return CapturedIO(stdout, stderr, outputs)
162
165
@@ -165,5 +168,6 b' class capture_output(object):'
165 sys.stderr = self.sys_stderr
168 sys.stderr = self.sys_stderr
166 if self.display and self.shell:
169 if self.display and self.shell:
167 self.shell.display_pub = self.save_display_pub
170 self.shell.display_pub = self.save_display_pub
171 sys.displayhook = self.save_display_hook
168
172
169
173
General Comments 0
You need to be logged in to leave comments. Login now