代码之家  ›  专栏  ›  技术社区  ›  Shital Shah

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

  •  0
  • Shital Shah  · 技术社区  · 6 年前

    我希望执行以下操作:

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

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

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

    到目前为止,我认为这样做的方式是通过jupyter_客户端。我在这里也找到了相关的问题: Executing code in ipython kernel with the KernelClient API .

    然而,这个问题集中在设置scaler值或运行代码上。如何将对象复制到Jupyter内核?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Shital Shah    6 年前

    以下是我的进展:

    首先,自从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控制台连接到IPython内核

    只需执行上面代码打印的命令:

    jupyter console --existing <full json filename>
    

    然后,如果在Jupyter控制台中键入d,将看到值32。

    如何从Jupyter笔记本连接到IPython内核

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

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

    这部分仍然不起作用。