Jupyter Notebook、Python:如何从函数内部调用魔法? [英] Jupyter Notebook, Python: How to call a magic from within a function?
问题描述
我正在使用 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: 无效语法
任何人都知道如何转换"魔术命令,以便可以从函数内部正确调用它(该函数保存在单独的文件中)
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?
显示它在 libsite-packagesipythoncoremagicsdisplay.py
If you use the ?
IPython builtin, you can see the path for the magics. For example, %%javascript?
shows that it is in libsite-packagesipythoncoremagicsdisplay.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:如何从函数内部调用魔法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!