Jupyter Notebook, Python: How to call a magic from within a function?

后端 未结 1 990
予麋鹿
予麋鹿 2021-01-02 16:59

I am using the Jupyter Notebook, and am trying to create a widget, based on a template found on Github.

The template uses at some point the magic %%javascript<

相关标签:
1条回答
  • 2021-01-02 17:24

    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")')
    

    EDIT: 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();""")
    
    0 讨论(0)
提交回复
热议问题