我有一个Python应用程序,它不时卡住,我不知道在哪里。
是否有任何方法向Python解释器发出信号,以显示正在运行的确切代码?
某种飞行中的堆叠痕迹?
相关问题:
从Python代码中的方法打印当前调用堆栈 检查正在运行的进程正在做什么:打印未检测的Python程序的堆栈跟踪
我有一个Python应用程序,它不时卡住,我不知道在哪里。
是否有任何方法向Python解释器发出信号,以显示正在运行的确切代码?
某种飞行中的堆叠痕迹?
相关问题:
从Python代码中的方法打印当前调用堆栈 检查正在运行的进程正在做什么:打印未检测的Python程序的堆栈跟踪
当前回答
我正在寻找一段时间的解决方案来调试我的线程,我发现它在这里感谢haridsv。我使用稍微简化的版本,使用traceback.print_stack():
import sys, traceback, signal
import threading
import os
def dumpstacks(signal, frame):
id2name = dict((th.ident, th.name) for th in threading.enumerate())
for threadId, stack in sys._current_frames().items():
print(id2name[threadId])
traceback.print_stack(f=stack)
signal.signal(signal.SIGQUIT, dumpstacks)
os.killpg(os.getpgid(0), signal.SIGQUIT)
为了满足我的需要,我还按名称筛选线程。
其他回答
可以使用PuDB,这是一个带有curses接口的Python调试器。只需添加
from pudb import set_interrupt_handler; set_interrupt_handler()
到您的代码中,并在需要中断时使用Ctrl-C。你可以继续使用c,如果你错过了它,想要再试一次,你可以再次打破多次。
我几乎总是处理多线程,主线程通常不做太多,所以最有趣的是转储所有堆栈(这更像Java的转储)。下面是一个基于这个博客的实现:
import threading, sys, traceback
def dumpstacks(signal, frame):
id2name = dict([(th.ident, th.name) for th in threading.enumerate()])
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %s(%d)" % (id2name.get(threadId,""), 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)
在运行代码时,您可以插入这个小片段,以查看格式化良好的打印堆栈跟踪。它假设在项目的根目录中有一个名为logs的文件夹。
# DEBUG: START DEBUG -->
import traceback
with open('logs/stack-trace.log', 'w') as file:
traceback.print_stack(file=file)
# DEBUG: END DEBUG --!
我是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。
从Austin 3.3开始,您可以使用-w/——where选项来发出当前堆栈跟踪。参见https://stackoverflow.com/a/70905181/1838793
如果您想查看正在运行的Python应用程序,以类似top的方式查看“活动”调用堆栈,可以使用austin-tui (https://github.com/p403n1x87/austin-tui)。你可以从PyPI安装它。
pipx install austin-tui
请注意,它需要austin二进制文件才能工作(https://github.com/p403n1x87/austin),但随后您可以使用
austin-tui -p <pid>