How can I start an interactive python/ipython session from the middle of my python program?


I have a python program which first does some tasks, and then in certain conditions goes into an interactive mode, where the user has access to an interactive python console with the current program’s scope. Right now I do this using the code module by calling code.InteractiveConsole(globals()).interact(”) (see

My problem is that the resulting interactive console lacks some functionalities that I usually get with the standard python console (i.e. the one you get by typing ‘python’ in a terminal), such as remembering the previous command, etc. Is there a way to get that same interactive console in the middle of my python program, or even better yet ipython’s interactive console?

Asked By: user3208430



Just use IPython.embed() where you’re currently using code.InteractiveConsole(globals()).interact('').

Make sure you’re importing IPython before you do that, though:

import IPython
# lots of code
# even more code
Answered By: Cody Piersall

You can use the builtin breakpoint() function (Available in Python 3.7+) to launch the interactive IPython shell with IPython.embed(). This is nice as it is shorter to type (and does not need an import).

By default breakpoint() launches a python debugger. To make it launch the ipython shell, you have to set the environmental variable PYTHONBREAKPOINT to be IPython.embed.

On Linux:

Run or add to your ~/.bashrc or ~/.profile:

export PYTHONBREAKPOINT="IPython.embed"

For more info about breakpoint(), see PEP 553

Answered By: np8
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.