Python 多线程脚本的事后调试

Python 多线程脚本的事后调试,python,multithreading,debugging,pdb,Python,Multithreading,Debugging,Pdb,我正在尝试调试多线程脚本。一旦出现例外情况 我想: 向监控系统报告(只需在下面的示例中打印) 停止整个脚本(包括所有其他线程) 在透视引发的异常中调用事后调试程序提示 我准备了一个相当复杂的例子来说明我是如何解决这个问题的: #!/usr/bin/env python import threading import inspect import traceback import sys import os import time def POST_PORTEM_DEBUGGER(type,

我正在尝试调试多线程脚本。一旦出现例外情况 我想:

  • 向监控系统报告(只需在下面的示例中打印)
  • 停止整个脚本(包括所有其他线程)
  • 在透视引发的异常中调用事后调试程序提示
  • 我准备了一个相当复杂的例子来说明我是如何解决这个问题的:

    #!/usr/bin/env python
    
    import threading
    import inspect
    import traceback
    import sys
    import os
    import time
    
    
    def POST_PORTEM_DEBUGGER(type, value, tb):
        traceback.print_exception(type, value, tb)
        print
        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
            import rpdb
            rpdb.pdb.pm()
        else:
            import pdb
            pdb.pm()
    
    sys.excepthook = POST_PORTEM_DEBUGGER
    
    
    
    class MyThread(threading.Thread):
    
        def __init__(self):
    
            threading.Thread.__init__(self)
            self.exception = None
            self.info = None
            self.the_calling_script_name = os.path.abspath(inspect.currentframe().f_back.f_code.co_filename)
    
        def main(self):
            "Virtual method to be implemented by inherited worker"
            return self
    
        def run(self):
            try:
                self.main()
            except Exception as exception:
                self.exception = exception
                self.info = traceback.extract_tb(sys.exc_info()[2])[-1]
                # because of bug http://bugs.python.org/issue1230540
                # I cannot use just "raise" under threading.Thread
                sys.excepthook(*sys.exc_info())
    
        def __del__(self):
            print 'MyThread via {} catch "{}: {}" in {}() from {}:{}: {}'.format(self.the_calling_script_name, type(self.exception).__name__, str(self.exception), self.info[2], os.path.basename(self.info[0]), self.info[1], self.info[3])
    
    
    
    
    class Worker(MyThread):
    
        def __init__(self):
            super(Worker, self).__init__()
    
        def main(self):
            """ worker job """
            counter = 0
            while True:
                counter += 1
                print self
                time.sleep(1.0)
                if counter == 3:
                    pass # print 1/0
    
    
    def main():
    
        Worker().start()
    
        counter = 1
        while True:
            counter += 1
            time.sleep(1.0)
            if counter == 3:
                pass # print 1/0
    
    if __name__ == '__main__':
        main()
    
    骗局

    sys.excepthook = POST_PORTEM_DEBUGGER
    
    如果不涉及线程,则可以完美工作。我发现,以防 我可以通过调用以下命令用于debuggig的多线程脚本:

    import rpdb; rpdb.set_trace()
    
    它非常适合定义断点,但我想调试 多线程脚本事后分析(在未修补异常被删除之后) 提出)。当我尝试在POST_PORTEM_调试器函数中使用rpdb时 使用多线程应用程序,我可以得到以下结果:

    Exception in thread Thread-1:
    Traceback (most recent call last):
        File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
            self.run()
        File "./demo.py", line 49, in run
            sys.excepthook(*sys.exc_info())
        File "./demo.py", line 22, in POST_PORTEM_DEBUGGER
            pdb.pm()
        File "/usr/lib/python2.7/pdb.py", line 1270, in pm
            post_mortem(sys.last_traceback)
    AttributeError: 'module' object has no attribute 'last_traceback'
    
    我看起来像

    sys.excepthook(*sys.exc_info())
    
    未设置
    提升
    命令的所有功能。 如果在main()中引发异常,我希望有相同的行为 在启动线程下。

    (我还没有测试我的答案,但在我看来…)

    调用
    pdb.pm
    (pm=“post mortem”)失败的原因很简单,因为在此之前没有“mortem”。即程序仍在运行

    查看
    pdb
    源代码,您可以找到
    pdb.pm
    的实现:

    def pm():
        post_mortem(sys.last_traceback)
    
    这让我猜测,您实际上想要做的是调用
    pdb.post_mortem()
    ,而不使用参数。看起来默认行为正是您所需要的

    还有一些源代码(请注意
    t=sys.exc_info()[2]
    行):

    这有助于:

    import sys
    from IPython.core import ultratb
    
    sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux',
        call_pdb=True, ostream=sys.__stdout__)
    

    谢谢你的提示。但它以ValeError异常结束(
    t为None
    )。调用
    sys.excepthook(*sys.exc_info())
    似乎没有设置
    raise
    的功能。
    import sys
    from IPython.core import ultratb
    
    sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux',
        call_pdb=True, ostream=sys.__stdout__)