飘逸的python - hack输出流便于调试

当项目有很多文件时,要找出控制台的输出是在哪里print出来的很麻烦,不过这事对于强大的python来说小菜一碟。

先上代码和效果,再说明。

 

import sys,traceback
class mystdout:
    stdout = sys.stdout
    def write(self,_str):
        if _str != '\n':
            filepath,lineno = traceback.extract_stack()[-2][0:2]
            mystdout.stdout.write("%s\t%s(%s)\n"%(_str,filepath,lineno))

sys.stdout = mystdout()

print 'foo'
print 'bar'


输出
foo test_stdout.py(11)
bar test_stdout.py(12)

 


当print 'foo'的时候,会调用sys.stdout.write(),不过因为sys.stdout = mystdout(),被重写了,所以实际调用的是mystdout类的write()方法。
在python中print会自动加换行符'\n',而且是单独sys.stdout.write('\n'),所以要if _str != '\n'。
再加上traceback获得文件名和行号,这样控制台的每个输出都能快速定位到在哪里print的了。


 

posted @ 2013-07-27 21:06  jlins  阅读(378)  评论(0编辑  收藏  举报