gpt4 book ai didi

python - 显示正在运行的 Python 应用程序的堆栈跟踪

转载 作者:IT老高 更新时间:2023-10-28 12:06:39 25 4
gpt4 key购买 nike

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

有什么方法可以向 Python 解释器发出信号以向您显示正在运行的确切代码?

某种即时堆栈跟踪?

相关问题:

最佳答案

我有用于这种情况的模块 - 一个进程将运行很长时间,但有时会因为未知和不可重现的原因而卡住。它有点hacky,只适用于unix(需要信号):

import code, traceback, signal

def debug(sig, frame):
"""Interrupt running process, and provide a python prompt for
interactive debugging."""
d={'_frame':frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)

i = code.InteractiveConsole(d)
message = "Signal received : entering python shell.\nTraceback:\n"
message += ''.join(traceback.format_stack(frame))
i.interact(message)

def listen():
signal.signal(signal.SIGUSR1, debug) # Register handler

要使用它,只需在程序启动时调用 listen() 函数(您甚至可以将其粘贴在 site.py 中以让所有 python 程序都使用它),然后让它运行。在任何时候,使用 kill 或在 python 中向进程发送 SIGUSR1 信号:

    os.kill(pid, signal.SIGUSR1)

这将导致程序在当前位置中断到 python 控制台,向您显示堆栈跟踪,并让您操作变量。使用 control-d (EOF) 继续运行(但请注意,您可能会在发出信号时中断任何 I/O 等,因此它不是完全非侵入性的。

我有另一个脚本做同样的事情,除了它通过管道与正在运行的进程通信(以允许调试后台进程等)。在这里发布有点大,但我已将其添加为 python cookbook recipe .

关于python - 显示正在运行的 Python 应用程序的堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/132058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com