是否有破解 pdb 内置打印的技巧? [英] Is there a trick to break on the print builtin with pdb?
本文介绍了是否有破解 pdb 内置打印的技巧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上是标题.
我试图在大型代码库中追踪虚假打印发生的位置,并且我想中断,或者在打印发生"时以某种方式获得堆栈跟踪.有什么想法吗?
I am trying to trace down where a spurious print happens in a large codebase, and I would like to break, or somehow get a stack trace whenever a print "happens." Any ideas?
推荐答案
对于这种特殊情况,您可以将 stdout
重定向到打印输出及其调用者的辅助类.你也可以打破它的一种方法.
For this particular case you can redirect stdout
to a helper class that prints the output and its caller. You can also break on one of its methods.
完整示例:
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()
.
You can also just print inspect.stack()
if you need more thorough information.
这篇关于是否有破解 pdb 内置打印的技巧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文