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
asked Jan 21, 2021 at 8:10
ppn029012
5802 gold badges6 silver badges21 bronze badges
1 Answer 1
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
callbackbut you don't define it - that would lead to anotherReferenceError - using
constis better than usingvarin JS Jupyter.notebook.kernelis the same asIPython.notebook.kernel
answered Jan 26, 2021 at 10:28
Jakub Žitný
9921 gold badge10 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
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.