飘逸的python

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

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

import sys,traceback
class mystdout:
    stdout = sys.stdout
    def write(self,_str):
        if _str != '
':
            filepath,lineno = traceback.extract_stack()[-2][0:2]
            mystdout.stdout.write("%s	%s(%s)
"%(_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会自动加换行符' ',而且是单独sys.stdout.write(' '),所以要if _str != ' '。
再加上traceback获得文件名和行号,这样控制台的每个输出都能快速定位到在哪里print的了。


原文地址:https://www.cnblogs.com/dyllove98/p/3220237.html