IPython Notebook以前的单元格内容

时间:2014-11-28 16:39:08

标签: ipython ipython-notebook

是否可以在IPython-Notebook单元格中获取上一个(上面)单元格内容?

我可以通过%capture magic函数看到以前的输出,但是我找不到如何获取之前的单元格内容。

4 个答案:

答案 0 :(得分:0)

我没有找到如何在单元格中获取前一个内容单元格。

但是我找到了另一个解决方案,创建一个自定义魔术笔记本功能来捕获单元格内容并使用它。

答案 1 :(得分:0)

您可以使用以下命令获取上次执行的单元格的内容:

In[len(In)-2]

答案 2 :(得分:0)

%recall jupyter_notebook_cell_number

应该为您提供在指定的特定笔记本单元jupyter_notebook_cell_number中最后执行的代码

答案 3 :(得分:0)

input catching system 的文档内容相当丰富。 返回输出(不是单元格输出内容)存储在_oh字典中,返回输出被添加到页面的.output_area DOM元素中作为具有 .output_subarea.output_text 和唯一 .output_result 类的 div 元素。打印或显示(IPython.display.display 也有前两个类,特别是打印有 .output_stream .output_stdout

_oh 是一个字典,整数与您在输入(.input_prompt div)左侧看到的相同。

换句话说,单元格内容的格式与预期一致。您实际上可以添加自己的 HTML。

from IPython.display import display, HTML
display(HTML('<h1>HELLO WORLD</h1>'))
display(HTML(<script>alert("hello world");</script>'))

这表明您可以在 Python 单元格中添加 JS — 但这有一个很大的缺陷。同样,在 JS 中你可以执行 python 代码。

IPython.notebook.kernel.execute("python_variable="+JSON.stringify(jsVariable));

但是,在内核空闲时执行 JS IPython 调用。因此,您必须等待单元格完成才能访问 python_variable。因此,在一个单元格中完成所有操作并使用常规单元格魔法是没有意义的。

因此,下面的 JS 魔术将给出一个 output 字典,其键是单元格编号,值是内容。如前所述,单元格内容已格式化,因此如果您想根据单元格中元素的类更改以下内容,您可以参考上述 CSS 类。

// querySelectorAll returns a NodeList which lacks most Array functions
// so destructuring into array
const outputs=[...document.querySelectorAll(".cell")].map(
        cell=> {
            const RawCellN=cell.querySelector(".input_prompt").innerText;
            // \xa0 is star. current: skip.
            if (RawCellN.match(/\[(\d+)\]/) === null) return null; 
            const cellN =  parseInt(RawCellN.match(/\[(\d+)\]/)[1]);
            const outputs= [...cell.querySelectorAll(".output_subarea")].map(
                subarea => subarea.innerText.trim());
            return [cellN, outputs.filter(out => out.length !== 0)];
        }
    ).filter(value => value !== null); // star cell was skipped.

// pass on the data to python
IPython.notebook.kernel.execute("outputs=dict("+JSON.stringify(outputs)+")")
相关问题