将IPython / Jupyter中的变量传递给html(%% html)块

the*_*ech 5 html python ipython jupyter jupyter-notebook

我想将简单的变量传递给Jupyter上的html单元:

单元格1:

a=5
Run Code Online (Sandbox Code Playgroud)

单元格2:

%%html
<html>
  <head>
    <script type="text/javascript">
    window.alert(a);
    </script>
  </head>
</html>
Run Code Online (Sandbox Code Playgroud)

这将返回错误:

Javascript error adding output!
ReferenceError: a is not defined
See your browser Javascript console for more details.
Run Code Online (Sandbox Code Playgroud)

the*_*ech 5

这是一个hacky解决方案:

a=5

html_code ="""
<html>
  <head>
    <script type="text/javascript">
    window.alert(%s);
    </script>
  </head>
</html>""" % a

from IPython.display import HTML
HTML(html_code)
Run Code Online (Sandbox Code Playgroud)