在Jupyter Notebook中将JS函数包装在python中的解决方法 [英] Workaround for wrapping a JS function in python in Jupyter notebook
问题描述
因此,在IPython Jupyter笔记本中,可以通过%% javascript
魔术单元语法或通过IPython.display.HTML
通过Python内核添加JavaScript函数,并且可以通过IPython.notebook.kernel.execute
更改JS中的Python变量.
So in an IPython Jupyter notebook one can add JavaScript functions via the %% javascript
magic cell syntax or via the Python kernel with IPython.display.HTML
and one can alter Python variables in JS with IPython.notebook.kernel.execute
.
但是,内核调用是在内核空闲时完成的.
However, the kernel call is done when the kernel is idle.
单元格1,添加了魔术单元格JS的功能.
cell 1, magic cell JS to add the function.
%%javascript
window.act = () => IPython.notebook.kernel.execute('flag = False');
单元2,Python内核
cell 2, python kernel
from IPython.display import display, HTML
flag = True
display(HTML('''<p id="newDOMElement">New DOM element added </div>
<script type="text/Javascript">
act();
$('#newDOMElement').append('<b>and changed</b>.');
</script>'''))
import time
time.sleep(2) #wait in case it's a JS async issue.
print('JS did not change Py variable.' if flag else 'JS successfully changed Py variable.')
>> New DOM element added and changed.
>> JS did not change Py variable.
结果表明JS正在工作并且正在更改#newDOMElement
元素.但是内核在等待时并没有改变.
实际上,一旦单元完成了内核,变量就会更改.如上所示.
The result shows the JS is working and changing the #newDOMElement
element. But the kernel did not change as it waited.
In fact, once the cell was done with the kernel, the variable changed. As show with this.
print('JS did not change Py variable.' if flag else 'JS successfully changed Py variable.')
>> JS successfully changed Py variable.
此实验意味着无法将JS函数包装在Python方法中,该方法在运行时会不断更改数据.有办法解决吗?
This experiment means that one cannot wrap the JS function in a Python method that changes data continually at runtime. Is there a way around this?
推荐答案
发送到内核的代码一次执行一个代码段.尽管您正在调用sleep
,但是单元仍在执行.因此,正如您所观察到的,由JS发送的代码段要等到单元格完成后才能执行.
Code sent to the kernel is executed one snippet at a time. Although you're calling sleep
, the cell is still executing. So the snippet sent by JS won't be executed until after the cell is done, as you've observed.
如果要异步执行某些操作,则可以通过Jupyter协议从浏览器向内核发送自定义消息,并在Python内核中安装自定义消息处理程序以对其进行处理. IPEP-8的以前的工作"部分链接了朝该方向的一些尝试:
If you want to do something asynchronously, you could send a custom message through the Jupyter protocol from the browser to the kernel, and install a custom message handler in the Python kernel to process it. Some attempts in that direction are linked in the "Previous work" section of IPEP-8:
https://github.com/ipython/ipython/wiki/IPEP-8:-Custom-messages-and-message-handlers#previous-work
这篇关于在Jupyter Notebook中将JS函数包装在python中的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!