是否有一个技巧打破内置的pdb打印?

时间:2012-05-24 17:32:15

标签: python printing stack-trace pdb

基本上,标题。

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

2 个答案:

答案 0 :(得分:4)

对于这种特殊情况,您可以将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()

答案 1 :(得分:1)

我唯一能想到的就是替换sys.stdout,例如使用codecs.getwriter('utf8')返回的streamwriter。然后你可以在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'
相关问题