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 am trying to use this answer , but trying my best to get it to work.

FWIW, this is the most recent Jupyter code (as per point) launched on Fedora 23. What are the prerequisites for making this work?

+3
source share
3 answers

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

or even simpler:

enter image description here

+7
source
 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 for this is that HTML takes some time to work, and you print it before the value is set. At sleep, a 3s latency seems sufficient, and a variable is assigned.

+1
source

The problem is that the HTML object is not the last in the cell. Therefore, it is ignored in the same way that any other value is not displayed without printing, unless it is the last in the cell. If you execute a cell with the following code, you will not see a warning window.

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

Make sure the last object in the cell is an HTML object and you will see a warning window.

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

Therefore, examples of Anthony Perot's work are separate cells. This should also work:

HTML and print in separated cells

0
source

All Articles