在 Python 程序中嵌入(创建)交互式 Python shell

是否可以在 Python 程序中启动交互式 Python shell?

我想使用这样一个交互式 Python shell (它正在运行 在里面我的程序的执行)来检查一些程序内部变量。

32578 次浏览

我有这个代码很久了,希望你能用得上。

要检查/使用变量,只需将它们放入当前名称空间。例如,我可以从命令行访问 var1var2

var1 = 5
var2 = "Mike"
# Credit to effbot.org/librarybook/code.htm for loading variables into current namespace
def keyboard(banner=None):
import code, sys


# use exception trick to pick up the current frame
try:
raise None
except:
frame = sys.exc_info()[2].tb_frame.f_back


# evaluate commands in current namespace
namespace = frame.f_globals.copy()
namespace.update(frame.f_locals)


code.interact(banner=banner, local=namespace)




if __name__ == '__main__':
keyboard()

但是 如果您想严格调试您的应用程序,我建议使用 IDE 或 Pdb (python 调试器)

密码模块提供了一个交互式控制台:

import readline # optional, will allow Up/Down/History in the console
import code
variables = globals().copy()
variables.update(locals())
shell = code.InteractiveConsole(variables)
shell.interact()

使用 IPython,您只需要调用:

from IPython.Shell import IPShellEmbed; IPShellEmbed()()

另一个技巧(除了已经建议的技巧之外)是打开一个交互式 shell 并导入(可能已经修改过的) python 脚本。在导入时,大多数变量、函数、类等(取决于如何准备)都是可用的,您甚至可以从命令行交互式地创建对象。因此,如果您有一个 test.py文件,您可以打开 Idle 或其他 shell,然后键入 import test(如果它在当前工作目录中)。

在 ipython 0.13 + 中,你需要这样做:

from IPython import embed


embed()