我有这个Python应用程序,它有时会卡住,我找不到位置。

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

某种动态堆栈跟踪?

相关问题:

  • Print current call stack from a method in Python code
  • Check what a running process is doing: print stack trace of an uninstrumented Python program
  • 最佳答案

    我有用于以下情况的模块-进程将长时间运行,但有时由于未知且不可复制的原因而卡住。它有点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

    09-04 03:08
    查看更多