Programmatically execute command in kernel

I am building a JupyterLab extension to automate deployments of Jupyter Notebooks into a cloud environment. I would like to have a button in my panel extension that, when pressed, will execute a command in the running kernel of the active notebook.

The behavior would be the same as having a cell with !command, but run programmatically when the button is pressed. So I wish to either create and the run programmatically a new cell (and then delete it) or execute directly a command in the kernel. Is this possible? Thanks!

Yes, it’s possible. You can send code snippets for execution to the kernel, no need for a cell. If it’s an IPython kernel with ! support, you can send the snippet with a prefixed !. For other languages, you’ll have to wrap the shell command in suitable code that starts a shell for execution.

Have you been able to achieve what you wanted? I am looking for the same functionality but I don’t know where to start actually. I just want to execute a python command in the active notebook kernel programmatically.

@LustigePerson Yes I have! You can send commands to a kernel, check out how we do it here https://github.com/kubeflow-kale/kale/blob/167aa8859b58918622bb9b742a08cf5807dee4d8/labextension/src/utils/NotebookUtils.tsx#L326

If you need to run a bash commands instead of a python command, just prepend with !

1 Like

Cool, thanks @Stefano_Fioravanzo

hey,
I wanted to create a lab extension that runs linux/python command while clicking on toolbar-button.
any idea how to achieve that?