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

78 投票
5 回答
36576 浏览
提问于 2025-04-16 15:21

在一个Python程序里,能不能启动一个交互式的Python命令行?

我想在我的程序运行的时候,使用这个交互式的Python命令行来查看一些程序内部的变量。

5 个回答

6

我这段代码已经有一段时间了,希望你能用得上。

要查看或使用变量,只需把它们放到当前的命名空间里。举个例子,我可以在命令行中访问 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调试器)

21

在ipython 0.13及以上版本中,你需要这样做:

from IPython import embed

embed()
76

code模块提供了一个可以互动的控制台:

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()

撰写回答