I would like to call the function say_hello
in Jupyter Notebook.
def say_hello():
print('hello')
%%javascript
//What have been tried
// Method 1
var kernel = IPython.notebook.kernel;
kernel.execute("say_hello()", {"output": callback});
// Method 2
Jupyter.notebook.kernel.execute("say_hello()")
Both methods throw ReferenceError
in the browser console.
VM5326:7 Uncaught ReferenceError: IPython is not defined
at send_message (<anonymous>:7:22)
at onClickSendMessage (<anonymous>:12:9)
at HTMLButtonElement.onclick (app.ipynb:1)
version : JupterLab 3.5, IPython 7.16, Python 3.9.1
Use ajax to Call Python From JavaScript. AJAX stands for Asynchronous JavaScript and XML. It utilizes the XMLHttpRequest object to communicate with servers.
Jupyter Notebooks are documents that contain a mix of live code (Python, R, Julia, JavaScript, and more), visualizations, and narrative text (Markdown). They're useful for breaking down concepts in a story telling form, where you can give some context and show the code below along with interactive visualizations.
The ReferenceError
that you're getting is caused by Jupyter and IPython globals not being available in Jupyter Lab at all. You'd have to write a JupyterLab extension yourself.
These things do work in Jupyter Notebooks though. Both of the methods that you tried are a good start but need some improvements.
We need 3 cells - Python, HTML, and JS one.
def say_hello():
print('hello')
%%html
<div id="result_output">
%%javascript
const callbacks = {
iopub: {
output: (data) => {
// this will print a message in browser console
console.log('hello in console')
// this will insert the execution result into "result_output" div
document.getElementById("result_output").innerHTML = data.content.text
}
}
};
const kernel = Jupyter.notebook.kernel
kernel.execute('say_hello()', callbacks)
Some notes:
callback
but you don't define it - that would lead to another ReferenceError
const
is better than using var
in JSJupyter.notebook.kernel
is the same as IPython.notebook.kernel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With