Embedding IPython
You can embed an IPython shell inside your own Python programs, giving scripts and long-running tools the full interactive experience: magic commands, tab completion, and rich object display. This is useful for interactive admin tools, data exploration scripts, and debugging loops.
IPython.embed()
from IPython import embed
def debug_hook():
print("entered debug_hook with state:")
embed() # drops into an interactive shell here
print("resuming after the shell exits")
debug_hook()
# %magic, Tab completion, and your local variables are all available
The embedded shell sees the local scope of the function it was called in; type exit() or Ctrl-D to return.
Embedding with Configuration
from IPython.terminal.embed import InteractiveShellEmbed
shell = InteractiveShellEmbed(
banner1="My tool debugger",
exit_msg="Bye from the tool.",
)
shell() # enter the shell when needed
IPython as a Library (IPython.core)
For programs that need IPython features without a full shell (e.g., running magic commands headlessly):
from IPython.core.interactiveshell import InteractiveShell
shell = InteractiveShell.instance()
shell.run_cell("%timeit range(1000)")
When to Embed
- Interactive CLIs: a data tool that drops users into a shell with its objects loaded.
- Debugging long-running processes without restarting: embed at a checkpoint.
- Education and demos: a script that invites the user to experiment live.
Summary
Embed an IPython shell in any script with IPython.embed() (scoped to the current function) or InteractiveShellEmbed with custom banners, and drive headless execution through InteractiveShell.instance().run_cell. Embedding turns a plain script into an interactive tool without changing its core logic.