IPython - 嵌入 IPython
嵌入 IPython
Section titled “嵌入 IPython”除了将 IPython 作为独立 shell 或通过 Jupyter 使用之外,你还可以将 IPython 内核(kernel)直接嵌入到自己的 Python 脚本或应用程序中。这对于在程序特定位置进行调试或检查程序状态非常有用。
使用 IPython.embed()
Section titled “使用 IPython.embed()”实现此功能的主要函数是 IPython.embed()。当你的脚本执行到这个函数调用时,它会暂停执行,并在你的终端中启动一个功能齐全的 IPython shell 会话。
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 = 10var2 = 20
result = complex_calculation(var1, var2)print(f"Final Result: {result}")当你运行 python my_app.py 时,脚本会正常执行,直到遇到 IPython.embed()。此时,你会看到类似以下内容的输出:
$ python my_app.pyAbout to perform final step...Dropping into IPython shell. Type 'exit' to continue.
Python 3.9.7 (...)Type 'copyright', 'credits' or 'license' for more informationIPython 8.0.1 -- An enhanced Interactive Python.
# -------- Inside the Embedded IPython Shell --------In [1]:访问本地作用域
Section titled “访问本地作用域”关键优点是嵌入式 IPython shell 可以访问调用 embed() 函数时的本地作用域(local scope)。你可以检查甚至修改脚本中的变量:
# -------- Inside the Embedded IPython Shell --------In [1]: print(intermediate_result)# 输出: 70
In [2]: print(a) # 'a' 来自函数的局部作用域# 输出: 10
In [3]: print(var1) # 'var1' 来自全局作用域# 输出: 10
In [4]: intermediate_result = 100 # 修改变量
In [5]: exit # 输入 exit 或按 Ctrl+D 退出嵌入式 shell退出嵌入式 shell 后,脚本会从中断的地方继续执行。在嵌入式会话中对局部变量进行的任何修改都会保留:
# -------- 脚本继续执行 --------Calculation finished.Final Result: 10000 # 因为 intermediate_result 被改成了 100- 调试: 在你怀疑有问题的地方插入
IPython.embed(),以便交互式地探索程序状态。 - 交互式探索: 在复杂的脚本中,进入 IPython shell,在继续之前对数据或对象进行实验。
- 配置/设置: 在较大的自动化流程中允许交互式的设置步骤。
嵌入 IPython 在脚本执行和交互式探索之间提供了一个强大的桥梁,使其成为 Python 开发人员的宝贵工具。