问题描述
我正在使用Jupyter Notebook,并试图基于Github上的模板创建小部件.
I am using the Jupyter Notebook, and am trying to create a widget, based on a template found on Github.
模板在某些时候使用了魔法%%javascript
.直接粘贴到笔记本的单元格中,效果很好.
The template uses at some point the magic %%javascript
. This works fine when directly pasted in the cells of the notebook.
但是,当我尝试使用小部件制作函数时,使用%%javascript
表达式会使它返回错误:
However when I tried to make a function out of the widget, having the %%javascript
expression makes it returns the error:
%%javascript SyntaxError: invalid syntax
任何人都知道如何转换"魔术命令,以便可以从函数内正确调用它(该函数保存在单独的文件中)
Anyone knows how to "convert" the magic command so that it can be invoked properly from within a function (the function is saved in a separate file)
推荐答案
如果使用内置的?
IPython,则可以看到魔术的路径.例如,%%javascript?
显示它在lib\site-packages\ipython\core\magics\display.py
If you use the ?
IPython builtin, you can see the path for the magics. For example, %%javascript?
shows that it is in lib\site-packages\ipython\core\magics\display.py
然后可以将其导入并作为标准使用.例如,如果您从笔记本计算机运行警报框,则会弹出以下对话框:
You can then just import it and use it as standard; for example, the following pops up an alert box if you run it from a notebook:
from IPython.core.magics.display import Javascript
Javascript('alert("hello world")')
要使您在注释中发布的示例正常工作,只需将要运行的Javascript括在引号中,然后使用Javascript
进行调用.替换为In[4]
会像往常一样弹出窗口,应该可以将其包含在普通的Python函数中.
To get the example you posted in the comments working, just wrap the Javascript you'd like to run in quotes and call it with Javascript
. Replacing In[4]
with this pops out the window as normal and should be fine to include in a normal Python function.
from IPython.core.magics.display import Javascript
Javascript("""$('div.inspector')
.detach()
.prependTo($('body'))
.css({
'z-index': 999,
position: 'fixed',
'box-shadow': '5px 5px 12px -3px black',
opacity: 0.9
})
.draggable();""")
这篇关于Jupyter Notebook,Python:如何从函数内部调用魔术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!