使用`%matplotlib inline`时,IPython InteractiveShell无法产生丰富的输出

时间:2016-05-10 16:01:39

标签: python matplotlib ipython jupyter

我正在为IPython应用程序编写一个自定义客户端(一个基于Web的IPython Notebook的图形表示),并且以编程方式管理IPython的最简单方法似乎是使用IPython.core.InteractiveShell实例。

考虑这个例子:当使用内联魔术执行使用丰富输出的Jupyter Notebook单元格时,Notebook会显示plt.show()内联的相应丰富表示(绘制图像):

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)
plt.show()

我希望能够通过其API(即InteractiveShell)以编程方式使用IPython来检索图像,如下所示:

from IPython.core.interactiveshell import InteractiveShell
shell = InteractiveShell()
result = shell.run_cell("...above code of the cell here...")
# result either gives an error when using %matplotlib inline or retrieves
# no useful info if no line magic is present

问题是InteractiveShell实例不接受%matplotlib内联魔术,在其enable_gui方法中给出NotImplementedError,该方法未实现。除了IPython的Github上的一个问题,我发现这方面的信息很少。

我知道我可以使用plt.save()手动执行此操作,但这对我来说似乎不对,因为我不想在每次需要另外丰富的结果表示时编写手动解释。我觉得我在IPython的工作方式中错过了很多,所以我在寻找结果时请求帮助。 Jupyter Notebook究竟做了什么来检索丰富的表示,也许可以通过其他方式轻松完成?我正在考虑使用jupyter_client,但现在看起来更令人困惑。

更新:

io.capture_output上下文管理器似乎是要走的路,但我只能捕获字符串输出(与使用%%捕获单元魔法几乎相同):

with io.capture_output() as captured:
    result = shell.run_cell(cell)
#captures strings only:

captured.stdout = {str} '<matplotlib.figure.Figure at 0x4f486d8>'

0 个答案:

没有答案