【发布时间】:2012-05-24 17:32:14
【问题描述】:
基本上就是标题。
我正在尝试追踪在大型代码库中发生虚假打印的位置,并且我想中断,或者每当打印“发生”时以某种方式获取堆栈跟踪。有什么想法吗?
【问题讨论】:
标签: python printing stack-trace pdb
基本上就是标题。
我正在尝试追踪在大型代码库中发生虚假打印的位置,并且我想中断,或者每当打印“发生”时以某种方式获取堆栈跟踪。有什么想法吗?
【问题讨论】:
标签: python printing stack-trace pdb
对于这种特殊情况,您可以将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() 添加到该类定义中。
我能想到的唯一方法是替换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'
【讨论】: