我有一个Python应用程序,它不时卡住,我不知道在哪里。
是否有任何方法向Python解释器发出信号,以显示正在运行的确切代码?
某种飞行中的堆叠痕迹?
相关问题:
从Python代码中的方法打印当前调用堆栈 检查正在运行的进程正在做什么:打印未检测的Python程序的堆栈跟踪
我有一个Python应用程序,它不时卡住,我不知道在哪里。
是否有任何方法向Python解释器发出信号,以显示正在运行的确切代码?
某种飞行中的堆叠痕迹?
相关问题:
从Python代码中的方法打印当前调用堆栈 检查正在运行的进程正在做什么:打印未检测的Python程序的堆栈跟踪
当前回答
如何调试任何函数在控制台:
创建使用pdb.set_trace()的函数,然后是要调试的函数。
>>> import pdb
>>> import my_function
>>> def f():
... pdb.set_trace()
... my_function()
...
然后调用创建的函数:
>>> f()
> <stdin>(3)f()
(Pdb) s
--Call--
> <stdin>(1)my_function()
(Pdb)
愉快的调试:)
其他回答
我把一些工具连接到一个正在运行的Python进程中,并注入一些代码来获得一个Python shell。
请看这里:https://github.com/albertz/pydbattach
从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>
我是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)
Python -dv yourscript.py
这将使解释器以调试模式运行,并为您提供解释器正在做什么的跟踪。
如果你想交互调试代码,你应该像这样运行它:
Python -m PDB yourscript.py
它告诉python解释器使用模块“pdb”(python调试器)运行你的脚本,如果你这样运行它,解释器将以交互模式执行,很像GDB