通过Comm将json数据发送到Jupyter Notebook Frontend

eja*_*ang 3 ipython-notebook jupyter

我想将一些任意数据发送到Jupyter Notebook前端.

根据http://jupyter-client.readthedocs.org/en/latest/messaging.html#opening-a-comm,Comm协议是一种发送自定义消息类型的方法,而不会像使用execute_requestmsg_type 那样使用hack .

在Python方面,我有

from ipykernel.comm import Comm 
c=Comm()
#c.open()
#c.send(data={'foo':'bar'})
Run Code Online (Sandbox Code Playgroud)

但是,在JavaScript方面,我在初始化Comm()时遇到错误:

Error: Class comm not found in registry at http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:12751:28 at Object.load_class (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:12736:16) at CommManager.comm_open (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:21802:37) at x.isFunction.i (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:89:5488) at Kernel._handle_iopub_message (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:23101:20) at Kernel._finish_ws_message (http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:22936:29) at http://localhost:8888/static/notebook/js/main.min.js?v=40e10638fcf65fc1c057bff31d165e9d:22926:44
Run Code Online (Sandbox Code Playgroud)

这个错误是什么意思?

eja*_*ang 9

弄清楚了 - IPyWidgets笔记本扩展提供了如何执行此操作的很好示例:https://github.com/ipython/ipywidgets

在JS方面:

var comm_manager=Jupyter.notebook.kernel.comm_manager
var handle_msg=function(msg){
    console.log('got msg'); 
    console.log(msg)
}

comm_manager.register_target('myTarget', function(comm,msg){
    console.log('opened comm');
    console.log(msg);
    // register callback
    comm.on_msg(handle_msg)
})
Run Code Online (Sandbox Code Playgroud)

然后在Python中

from ipykernel.comm import Comm 
c=Comm(target_name='myTarget',data={})
c.send('hello')
Run Code Online (Sandbox Code Playgroud)

浏览器控制台中的响应:

opened comm
VM4511:3 Object {parent_header: Object, msg_type: "comm_open", msg_id: "331ba915-0b45-4421-b869-7d9794d72113", content: Object, header: Object…}
VM4464:2 got msg
VM4464:2 Object {parent_header: Object, msg_type: "comm_msg", msg_id: "9fdc83c8-49c5-4629-aa43-7ddf92cb4f5e", content: Object, header: Object…}
Run Code Online (Sandbox Code Playgroud)