Skip to content

IPython - Embedding IPython

Beyond using IPython as a standalone shell or through Jupyter, you can also embed an IPython kernel directly into your own Python scripts or applications. This is incredibly useful for debugging or inspecting the state of your program at a specific point.

The primary function for this is IPython.embed(). When your script reaches this function call, it will pause execution and launch a fully functional IPython shell session right there in your terminal.

my_app.py
import IPython
def complex_calculation(a, b):
intermediate_result = a * 5 + b
print("About to perform final step...")
# --- Embedding IPython here ---
print("Dropping into IPython shell. Type 'exit' to continue.")
IPython.embed()
# --------------------------------
final_result = intermediate_result ** 2
print("Calculation finished.")
return final_result
var1 = 10
var2 = 20
result = complex_calculation(var1, var2)
print(f"Final Result: {result}")

When you run python my_app.py, the script will execute normally until it hits IPython.embed(). At that point, you’ll see output similar to this:

$ python my_app.py
About to perform final step...
Dropping into IPython shell. Type 'exit' to continue.
Python 3.9.7 (...)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.0.1 -- An enhanced Interactive Python.
# -------- Inside the Embedded IPython Shell --------
In [1]:

The key benefit is that the embedded IPython shell has access to the local scope where embed() was called. You can inspect and even modify variables from your script:

# -------- Inside the Embedded IPython Shell --------
In [1]: print(intermediate_result)
# Output: 70
In [2]: print(a) # 'a' is from the function's scope
# Output: 10
In [3]: print(var1) # 'var1' is from the global scope
# Output: 10
In [4]: intermediate_result = 100 # Modify a variable
In [5]: exit # Type exit or press Ctrl+D to leave the embedded shell

After exiting the embedded shell, the script resumes execution from where it left off. Any modifications made to local variables within the embedded session will persist:

# -------- Script Resumes Execution --------
Calculation finished.
Final Result: 10000 # Because intermediate_result was changed to 100
  • Debugging: Insert IPython.embed() at points where you suspect issues to interactively explore the program’s state.
  • Interactive Exploration: In complex scripts, drop into an IPython shell to experiment with data or objects before continuing.
  • Configuration/Setup: Allow interactive setup steps within a larger automated process.

Embedding IPython provides a powerful bridge between scripted execution and interactive exploration, making it a valuable tool for Python developers.