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.
- let's just define the method we want to invoke from JS in Python.
def say_hello():
print('hello')
- We need to create a cell output, where the JS will be writing the results of the execution.
%%html
<div id="result_output">
- We execute the Python function, and handle the execution result in a callback. From the callback, we'll fill the result text into the output that we created above.
%%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:
- your 2nd method would be good enough if you didn't need to see the result, the execution is executed, just the results from kernel are not handled (you can see that in Network tab in browser devtools in Websocket request messages)
- in your method 1 you use
callback but you don't define it - that would lead to another ReferenceError
- using
const is better than using var in JS
Jupyter.notebook.kernel is the same as IPython.notebook.kernel
printandreturn. Cause, i think in your method 2 you are running source code likeprint. And, insay_hellocommand you are usingprintfunction also. So, i think if you writereturninstead ofprintinsay_hellocommand. I think it will work...IPythonandJupyterobjects in my JS code.