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

2024-04-25 06:03:54 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

在ipython 0.13+中,您需要执行以下操作:

from IPython import embed

embed()

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

我已经有这个代码很长时间了,希望你能使用它。

要检查/使用变量,只需将它们放入当前命名空间。例如,我可以从命令行访问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 debugger)

相关问题 更多 >