How to get the results of python commands in Google Colab from javascript using colab.global.notebook.kernel.execute()

Viewed 306

Here's the thing, I have a google colab notebook and I'm needing to run python commands from javascript when I run a cell.

When I try to run the command colab.global.notebook.kernel.execute('5+3') just to test the output, in the promise response I get the following:

enter image description here

As you can see in the image, the result of the 5 + 3 operation is not returned in the promise response.

In Jupyter Notebook it is possible to get the response easily with a Javascript code like the following:

new Promise((resolve, reject) => {
    var callback = {
        iopub: {
            output: (data) => {
                if (data.content.text) {
                    resolve(data.content.text.trim());
                } else if (data.content.ename && data.content.evalue) {
                    resolve(`{"ename": "${data.content.ename}", "evalue": "${data.content.evalue}"}`);
                } else {
                    resolve('');
                }
            }
        }
    };
    Jupyter.notebook.kernel.execute(`${pythonCode}`, callback);
})

In JupyteLab it is possible to get the response by creating a jlab extension that contains the following:

future(JupyterLab[kernelId].context.sessionContext.session?.kernel.requestExecute({code}));

I've tried to do something similar to what I'm doing in Jupyter Notebook and Lab but with the Google Colab kernel (colab.global.notebook.kernel.execute('5+3')) but I can't get the response of the python command I am running.

I've searched for documentation on this but couldn't find anything and also explored the colab object completely but still nothing.

Any help or workaround would be appreciated. Thanks!

0 Answers
Related