在单独的命名空间中执行另一个ipython笔记本 [英] Execute another ipython notebook in a separate namespace

查看:89
本文介绍了在单独的命名空间中执行另一个ipython笔记本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用这个例子中的一些非常好的代码运行一个来自另一个的ipython笔记本,我(基本上)在下面复制。这是组织我的代码的一种非常好的方式。

I've been using some very nice code from this example to run one ipython notebook from another, which I (basically) copy below. This turns out to be a very nice way to organize my code.

但是现在,我想比较一些我用相同的同情表达式编写的同情表达式其他人已编码。由于存在一些名称冲突,我希望能够在自己的命名空间中执行这两个笔记本,这样如果Bob和我都定义了一个sympy表达式 x ,我只能评估

But now, I want to compare some sympy expressions that I've coded up with roughly equivalent sympy expressions that someone else has coded up. And since there are some name clashes, I'd like to be able to execute the two notebooks in their own namespaces, so that if Bob and I both define a sympy expression x, I can just evaluate

Bob.x - Me.x

看看它们是否相同(或找出它们的差异)。 [请注意,使用此Bunch对象之类的内容,可以轻松地将命名空间字典更改为dottable命名空间。]

to see if they are the same (or find their differences). [Note that it's easy to change a namespace dictionary into a "dottable" namespace using something like this Bunch object.]

这是函数:

def exec_nb(nbfile):
    from io import open
    from IPython.nbformat import current
    with open(nbfile) as f:
        nb = current.read(f, 'json')
    ip = get_ipython()
    for cell in nb.worksheets[0].cells:
        if cell.cell_type != 'code':
            continue
        ip.run_cell(cell.input)

基本问题是 get_ipython 获取当前运行ipython实例,然后 run_cell 执行该实例当前命名空间中其他笔记本的单元格。

The basic problem is the get_ipython gets the currently running ipython instance, and then run_cell executes the cells from the other notebook in the current namespace of that instance.

我无法弄清楚如何改变这一点。例如,使用不同的命名空间在 exec 中运行整个命令仍然会找到当前的ipython实例,并使用该命名空间。

I can't figure out how to change this. For example, running the whole command in exec with a different namespace still finds the current ipython instance, and uses that namespace.

另外,两个笔记本实际上都需要在ipython中运行;我无法将它们导出到脚本并在命名空间中执行脚本。

Also, both notebooks actually need to be run in ipython; I can't export them to a script and execute the scripts in a namespace.

推荐答案

对于记录,链接Jakob指向现在已经移动了这里,并回答了我的问题。完美地提问。

For the record, the link Jakob pointed to has now moved here, and answered my question perfectly.

这篇关于在单独的命名空间中执行另一个ipython笔记本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆