【问题标题】:Is there a trick to break on the print builtin with pdb?是否有破解 pdb 内置 print 的技巧?
【发布时间】:2012-05-24 17:32:14
【问题描述】:

基本上就是标题。

我正在尝试追踪在大型代码库中发生虚假打印的位置,并且我想中断,或者每当打印“发生”时以某种方式获取堆栈跟踪。有什么想法吗?

【问题讨论】:

    标签: python printing stack-trace pdb


    【解决方案1】:

    对于这种特殊情况,您可以将stdout 重定向到打印输出及其调用者的帮助类。您也可以中断其中一种方法。

    完整示例:

    import sys
    import inspect
    
    class PrintSnooper:
        def __init__(self, stdout):
            self.stdout = stdout
        def caller(self):
            return inspect.stack()[2][3]
        def write(self, s):
            self.stdout.write("printed by %s: " % self.caller())
            self.stdout.write(s)
            self.stdout.write("\n")
    
    def test():
        print 'hello from test'
    
    def main():
        # redirect stdout to a helper class.
        sys.stdout = PrintSnooper(sys.stdout)
        print 'hello from main'
        test()
    
    if __name__ == '__main__':
        main()
    

    输出:

    printed by main: hello from main
    printed by main: 
    
    printed by test: hello from test
    printed by test: 
    

    如果您需要更全面的信息,也可以直接打印 inspect.stack()

    【讨论】:

    • 太棒了...我希望有一种方法可以在任意内置函数上执行此操作,但我能够用它来追踪打印。非常感谢!
    • 如果您的应用程序使用它,您可能需要将def flush(self): self.stdout.flush() 添加到该类定义中。
    【解决方案2】:

    我能想到的唯一方法是替换sys.stdout,例如用codecs.getwriter('utf8') 返回的流写入器。然后,您可以在 pdb 中的 write 方法上设置断点。或者用调试代码替换它的write方法。

    import codecs
    import sys
    
    writer = codecs.getwriter('utf-8')(sys.stdout) # sys.stdout.detach() in python3
    old_write = writer.write
    
    def write(data):
        print >>sys.stderr, 'debug:', repr(data)
        # or check data + pdb.set_trace()
        old_write(data)
    
    writer.write = write
    sys.stdout = writer
    
    print 'spam', 'eggs'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 2022-11-02
      • 1970-01-01
      相关资源
      最近更新 更多