用于多个单元格的自定义IPython魔术命令



如何构建一个自定义的IPython魔术命令:

  1. 在运行单元格之前先运行一段代码
  2. 只需要调用一次就可以应用于笔记本的每个单元格

类似情况
CCD_ 1,CCD_ 2,%doctest_mode

示例

In [1]: %myMagic 1
Out[1]: myMagic is: ON
In [2]: x = 1
Out[2]: 'Hello World'
In [3]: x
Out[3]: 'Hello World'
...:  1
In [4]: %myMagic 0
Out[4]: myMagic is: OFF
In [5]: y=x+1
...: y
Out[5]: 2

我目前正在开发一个Jupyter扩展,在内核执行之前,我希望将代码单元的全部内容封装在特定的上下文管理器中,其中代码单元是基于各种用户可配置逻辑封装的还是不基于这些逻辑封装的。

据我所知,不可能使用magics做你想做的事情,因为magics无法连接到IPython内核本身的执行机制。据我所知,你提到的所有魔法都是通过更改某个特定模块或类中的设置来工作的,然后控制笔记本其余部分中该模块/类的全局行为。

我所要做的是从扩展端处理这一问题,在前端Javascript中获取单元代码,注入上下文管理器,缩进块,然后提交编辑后的代码供内核执行。作为参考,截至本文撰写之时,我的在制品在这里;一个简单的实现是:

define([
'notebook/js/codecell'
], function (codecell) {
"use strict";
var CodeCell = codecell.CodeCell
return {
load_ipython_extension: function () {
/* Store the original .execute() before overriding,
* for use in the overridden method
*/ 
var orig_execute = CodeCell.prototype.execute;
// Override .execute()
CodeCell.prototype.execute = function (stop_on_error) {
var orig_text = this.get_text();
var new_text = orig_text;
/* == Make whatever modifications to new_text == */
/* Rewrite the cell text, make the .execute() call,
* and restore the original cell text
*/
this.set_text(new_text);
orig_execute.call(this, stop_on_error);
this.set_text(orig_text);
};
}
};
});

最新更新