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

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

某种飞行中的堆叠痕迹?

相关问题:

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


当前回答

我想对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)

其他回答

我是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。

我想对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)

Pydb值得一看,它是“松散地基于gdb命令集的Python调试器的扩展版本”。它包括信号管理器,可以在发送指定信号时启动调试器。

2006年的“代码之夏”项目研究了在名为mpdb的模块中向pydb添加远程调试功能。

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

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

我不知道有什么类似于java对SIGQUIT的响应,所以您可能必须将其构建到应用程序中。也许您可以在另一个线程中创建一个服务器,以便在响应某种类型的消息时获得堆栈跟踪?