因此,在 IPython Jupyter 笔记本中,您可以通过%% javascript魔术单元语法或通过 Python 内核添加 JavaScript 函数,并且可以使用 .jsIPython.display.HTML更改 JS 中的 Python 变量IPython.notebook.kernel.execute。但是,内核调用是在内核空闲时完成的。单元格1,魔术单元JS添加功能。%%javascriptwindow.act = () => IPython.notebook.kernel.execute('flag = False');单元 2,python 内核from IPython.display import display, HTMLflag = Truedisplay(HTML('''<p id="newDOMElement">New DOM element added </div> <script type="text/Javascript"> act(); $('#newDOMElement').append('<b>and changed</b>.'); </script>'''))import timetime.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元素。但是内核在等待时并没有改变。事实上,一旦单元用内核完成,变量就会改变。正如这个所示。print('JS did not change Py variable.' if flag else 'JS successfully changed Py variable.')>> JS successfully changed Py variable.这个实验意味着不能将 JS 函数包装在一个在运行时不断改变数据的 Python 方法中。有没有解决的办法?
添加回答
举报
0/150
提交
取消