background-zmq-ipython icon indicating copy to clipboard operation
background-zmq-ipython copied to clipboard

Add instruction on how to use the shell programmatically

Open user202729 opened this issue 6 months ago • 1 comments

Something like this would suffice.

To get the path to the connection filename:

from background_zmq_ipython import init_ipython_kernel, IPythonBackgroundKernelWrapper  # type: ignore
kernel_wrapper: IPythonBackgroundKernelWrapper = init_ipython_kernel(logger=logging.Logger("IPython", level=logging.INFO))
# if logger=... is removed, it will print "To connect another client to this IPython kernel" ...
print(kernel_wrapper.connection_filename)

To run a cell in the same process as the one that calls init_ipython_kernel (there's a small race condition, you need to wait for a while after kernel_wrapper is created):

from IPython.core.interactiveshell import InteractiveShell
ipython_shell = InteractiveShell.instance()
result = ipython_shell.run_cell("a=1")

The result object would contain .result and .error_in_exec fields which may be useful. Unlike the default IPython shell, the output will not be printed to stdout by default.

Might also be useful for kernel_wrapper object to expose .get_shell().

user202729 avatar Jun 12 '25 05:06 user202729

You mean to add this to the README? Feel free to make a PR. I would suggest to add it right before the "Alternatives / related links".

Might also be useful for kernel_wrapper object to expose .get_shell().

Also feel free to make a PR about that.

albertz avatar Jun 12 '25 07:06 albertz