我有一个Python应用程序,它不时卡住,我不知道在哪里。

是否有任何方法向Python解释器发出信号,以显示正在运行的确切代码?

某种飞行中的堆叠痕迹?

相关问题:

从Python代码中的方法打印当前调用堆栈 检查正在运行的进程正在做什么:打印未检测的Python程序的堆栈跟踪


当前回答

使用inspect模块。

进口检查 帮助(inspect.stack) 模块检查中的函数堆栈帮助:

堆栈(上下文= 1) 返回调用者帧上面堆栈的记录列表。

我发现它确实很有帮助。

其他回答

在这里真正帮助我的是spiv的技巧(如果我有声望分数,我会投票并评论),即从一个未准备好的Python进程中获得堆栈跟踪。除非我修改了gdbinit脚本,否则它无法工作。所以:

下载https://svn.python.org/projects/python/trunk/Misc/gdbinit并将其放在~/.gdbinit中 编辑它,将PyEval_EvalFrame更改为PyEval_EvalFrameEx [edit:不再需要;链接的文件在2010-01-14已经有此更改] 附加gdb: gdb -p PID 获取python堆栈跟踪:pystack

我是GDB阵营的python扩展。关注https://wiki.python.org/moin/DebuggingWithGdb,这意味着

DNF install GDB python-debuginfo或sudo apt-get install GDB python2.7-dbg GDB python <运行进程>的pid py-bt

同时考虑info threads和thread apply all py-bt。

我把一些工具连接到一个正在运行的Python进程中,并注入一些代码来获得一个Python shell。

请看这里:https://github.com/albertz/pydbattach

可以使用PuDB,这是一个带有curses接口的Python调试器。只需添加

from pudb import set_interrupt_handler; set_interrupt_handler()

到您的代码中,并在需要中断时使用Ctrl-C。你可以继续使用c,如果你错过了它,想要再试一次,你可以再次打破多次。

我想对haridsv的回答加一个评论,但我缺乏这样做的声誉:

我们中的一些人仍然停留在2.6以上的Python版本(thread .ident需要),所以我让代码在Python 2.5中工作(尽管没有显示线程名称):

import traceback
import sys
def dumpstacks(signal, frame):
    code = []
    for threadId, stack in sys._current_frames().items():
            code.append("\n# Thread: %d" % (threadId))
        for filename, lineno, name, line in traceback.extract_stack(stack):
            code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
            if line:
                code.append("  %s" % (line.strip()))
    print "\n".join(code)

import signal
signal.signal(signal.SIGQUIT, dumpstacks)