基本上,标题。
我试图追踪大型代码库中发生虚假打印的位置,并且我想在打印“发生”时中断或以某种方式获取堆栈跟踪。有任何想法吗?
对于这种特殊情况,您可以重定向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()
Output:
printed by main: hello from main
printed by main:
printed by test: hello from test
printed by test:
您也可以只打印inspect.stack()
如果您需要更全面的信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)