John Schmitt
John Schmitt

Reputation: 1218

How to pass variables from javascript to python in Jupyter?

As I understand it, I should be able to print the variable foo in the snippet below.

from IPython.display import HTML
HTML('''
    <script type="text/javascript">
        IPython.notebook.kernel.execute("foo=97")
    </script>
     ''')
print(foo)

Instead, I see this error message:

NameErrorTraceback (most recent call last)
<ipython-input-2-91b73ee49ec6> in <module>()
      5     </script>
      6      ''')
----> 7 print(foo)

NameError: name 'foo' is not defined

I'm trying to use this answer but struggling to make it work.

FWIW, this is the latest Jupyter code (according to pip) running on Fedora 23. What are the prerequisites to make this work?

Upvotes: 9

Views: 9601

Answers (4)

uhetz
uhetz

Reputation: 412

If you have a function in your js code that takes some parameters and you would like to call that from Jupyter Notebook, you can do following:

from IPython.display import HTML, Javascript

HTML('<script src="./yourfile.js"></script>
Javascript('yourFunction(%s)' % parameter)

In that case, that you are using pandas's dataframe, the last line should be looking following:

Javascript('yourFunction(%s)' % parameter.to_json(orient='records'))

Links:

Instead of '%' you can choose format function

Upvotes: 3

guiferviz
guiferviz

Reputation: 160

The problem here is that the HTML object is not the last one in the cell. So it is ignored in the same way any other value without print is not shown, unless it is the last one in the cell. If you execute a cell with the next code, you won't see any alert window.

HTML('''
    <script type="text/javascript">
        alert("hello")
    </script>
''')
print("hello")

Ensure that the last object in the cell is the HTML object and you will see the alert window.

HTML('''
    <script type="text/javascript">
        alert("hello")
    </script>
''')

That's why the examples of Anthony Perot work, they are separated cells. This should also work:

HTML and print in separated cells

Upvotes: 2

SidML
SidML

Reputation: 191

from IPython.display import HTML
HTML('''
<script type="text/javascript">
    IPython.notebook.kernel.execute("foo=11")
</script>
 ''')
from time import sleep
sleep(3)
print(foo)

The reason this works is the HTML takes some time to work and you print it even before the value is set. With sleep, the wait time of 3s seems to be enough and the variable gets assigned.

Upvotes: 2

DevLounge
DevLounge

Reputation: 8447

This is how I made your code work: enter image description here

or even simpler:

enter image description here

Upvotes: 14

Related Questions