显示来自正在运行的 Python 应用程序的堆栈跟踪 [英] Showing the stack trace from a running Python application

查看:33
本文介绍了显示来自正在运行的 Python 应用程序的堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 Python 应用程序时不时卡住,我找不到在哪里.

I have this Python application that gets stuck from time to time and I can't find out where.

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

Is there any way to signal Python interpreter to show you the exact code that's running?

某种即时堆栈跟踪?

相关问题:

推荐答案

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

I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals):

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.
Traceback:
"
    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 信号:

To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python:

    os.kill(pid, signal.SIGUSR1)

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

This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive.

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

I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a python cookbook recipe.

这篇关于显示来自正在运行的 Python 应用程序的堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆