Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. This works fine when directly pasted in the cells of the notebook.

However when I tried to make a function out of the widget, having the %%javascriptexpression 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)

like image 577
Radar Avatar asked Jan 10 '17 05:01

Radar


People also ask

What does %% do in Jupyter notebook?

Both ! and % allow you to run shell commands from a Jupyter notebook. % is provided by the IPython kernel and allows you to run "magic commands", many of which include well-known shell commands. ! , provided by Jupyter, allows shell commands to be run within cells.

What is %% capture in jupyter?

Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable.

What is %% time in Jupyter notebook?

%%time measures how long it took something to run.


1 Answers

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();""")
like image 132
Randy Avatar answered Oct 01 '22 00:10

Randy