How to pass variables from javascript to python in

2019-06-23 23:11发布

问题:

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?

回答1:

This is how I made your code work:

or even simpler:



回答2:

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.



回答3:

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: