如何在程序中启动python控制台(以便于调试)?

2024-04-19 04:15:52 发布

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

经过多年的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 ...

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


Tags: to数据方法绘图is编程code事情
3条回答

我发现最好的解决方案是使用“代码”模块。我现在可以在代码中的任何地方调用“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"

^{}模块包含用于启动REPL的类。在

使用pdb库。在

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

import pdb; pdb.set_trace()

这将使您进入pdb控制台。在

pdb控制台与标准Python控制台不完全相同,但它可以完成大部分相同的工作。另外,在我的~/.pdbrc中,我有:

^{pr2}$

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

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

相关问题 更多 >