从Python脚本将变量复制到Jupyter内核

时间:2018-12-10 14:29:11

标签: python jupyter-notebook ipython jupyter

我希望执行以下操作:

  1. 从Python脚本中,连接到现有的Jupyter内核。

  2. 将Python脚本中可用的对象复制到Jupyter内核。

  3. 从Jupyter笔记本访问该对象。

到目前为止,我知道通过jupyter_client可以做到这一点。我还在这里找到了相关问题:Executing code in ipython kernel with the KernelClient API

但是,这个问题集中在设置缩放器值或运行代码上。如何将对象复制到Jupyter内核?

1 个答案:

答案 0 :(得分:1)

这是我走了多远:

首先,自IPython 4.0以来,很多事情都发生了变化,因此,无论有多少相关示例都没有用。最重要的是,文档不存在。

如何在Python脚本中实例化IPython内核

您可以执行以下操作:

from jupyter_client import KernelManager

def main():
    km = KernelManager()
    km.start_kernel()

    cf = km.connection_file
    print("To connect a client: jupyter console --existing ", cf)

    kc = km.client()
    kc.start_channels()
    try:
        kc.wait_for_ready()
    except RuntimeError:
        kc.stop_channels()
        km.shutdown_kernel()
        raise

    # executes Python statement to create global variable named d 
    # and assign it value 32
    kc.execute('d=32')

    input("Press Enter to continue...")

if __name__ == '__main__':
    main()

如何从Jupyter Console连接到IPython内核

只需执行以上代码打印的命令即可:

jupyter console --existing <full json filename>

然后,如果您在Jupyter Console中键入d,则将看到值32。

如何从Jupyter Notebook连接到IPython内核

这仍然是一个艰难的过程。主要问题是Jupyter笔记本电脑坚持拥有自己的内核,并且没有任何选择可以连接到现有内核。唯一的方法是创建自己的内核管理器类,其中的一个示例是here,但它似乎不适用于更新的IPython。然后,通过指定使用内核管理器类来调用Notebook:

jupyter notebook \
  --NotebookApp.kernel_manager_class=extipy.ExternalIPythonKernelManager \
  --Session.key='b""'

这部分仍然无法正常工作。