【问题标题】:How can I start the python console within a program (for easy debugging)?如何在程序中启动 python 控制台(以便于调试)?
【发布时间】:2010-12-22 17:18:52
【问题描述】:

在 Matlab 中研究编程多年后,我怀念通过交互式控制台暂停程序并检查变量、绘图、保存/修改数据等,然后继续执行的方式。

有没有办法在 python 中做同样的事情?

例如:


   # ... python code ...
   RunInterpreter
   # Interactive console is displayed, so user can inspect local/global variables
   # User types CTRL-D to exit, and script then continues to run
   # ... more python code ...

这将使调试更容易。非常感谢您的建议,谢谢!

【问题讨论】:

    标签: python console debugging interpreter


    【解决方案1】:

    使用pdb 库。

    我在 Vim 中将此行绑定到 <F8>

    import pdb; pdb.set_trace()
    

    这会让你进入pdb 控制台。

    pdb 控制台与标准 Python 控制台完全不同……但它会做大部分相同的事情。另外,在我的~/.pdbrc 中,我有:

    alias i from IPython.Shell import IPShellEmbed as IPSh; IPSh(argv='')()
    

    这样我就可以使用i 命令从pdb 进入“真正的”iPython shell:

    (pdb) i
    ...
    In [1]:
    

    【讨论】:

    • 嘿,不错的 iPython!一定要试试看。
    【解决方案2】:

    我发现的出色解决方案是使用“代码”模块。我现在可以从代码中的任何位置调用“DebugKeyboard()”,解释器提示将弹出,允许我检查变量并运行代码。 CTRL-D 将继续程序。

    import code
    import sys    
    
    def DebugKeyboard(banner="Debugger started (CTRL-D to quit)"):
    
        # 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)
    
        print "START DEBUG"
        code.interact(banner=banner, local=namespace)
        print "END DEBUG"
    

    【讨论】:

      【解决方案3】:

      code 模块包含用于启动 REPL 的类。

      【讨论】:

      • 有趣,我不知道。我会试一试的。
      【解决方案4】:

      查看Python debugger。总之,你可以插入

      import pdb; pdb.set_trace()
      

      在您要调试的程序中的任何位置。 (请注意,您应该在发布版本中删除这些!)

      【讨论】:

        【解决方案5】:

        pdb 是您要查找的内容 - 只需调用 pdb.set_trace() 即可进入调试器。

        【讨论】:

          【解决方案6】:

          这是一个更好、更简单的解决方案,适用于 Python 3.8 https://stackoverflow.com/a/1396386/4566456

          如果安装了 IPython,功能会更强大 https://stackoverflow.com/a/8152484/4566456

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-07-20
            • 2012-09-06
            • 1970-01-01
            • 2017-12-18
            • 1970-01-01
            • 2015-05-22
            • 1970-01-01
            相关资源
            最近更新 更多