Skip to content

Instantly share code, notes, and snippets.

@craigsdennis
Created June 12, 2018 16:30
Show Gist options
  • Save craigsdennis/ddfaa99a6291f05fef879329821872ee to your computer and use it in GitHub Desktop.
Save craigsdennis/ddfaa99a6291f05fef879329821872ee to your computer and use it in GitHub Desktop.
Run Python code from JavaScript in a Jupyter notebook
// %%javascript
window.executePython = function(python) {
return new Promise((resolve, reject) => {
var callbacks = {
iopub: {
output: (data) => resolve(data.content.text.trim())
}
};
Jupyter.notebook.kernel.execute(`print(${python})`, callbacks);
});
}
// Use it in any Jupyter JS/HTML cell like this
%%javascript
window.executePython("1 + 1")
.then(result => console.log(result)); // Logs 2
// You can access any defined object/method in the notebook
// I suggest writing a function that returns your data as JSON and just calling the function.
@lucharo
Copy link

lucharo commented Feb 28, 2021

Hi, thanks for posting the snippet, I am surprised there aren't more examples of this online. Would you be able to explain what's going in the executePython function for a JavaScript beginner? I am wondering if there is a need for a promise or if the code could made shorter?

@janpfeifer
Copy link

Actually this doesn't work in JUpyter-Lab:

...
VM466:8 Uncaught (in promise) ReferenceError: Jupyter is not defined
...

Somehow Jupyter object is not visible from inside the notebook. Would you have any ideas these days how to communicate with the Kernel (ipython or other) from Javascript ?

cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment