飘逸的python - hack输出流便于调试
生活随笔
收集整理的這篇文章主要介紹了
飘逸的python - hack输出流便于调试
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
當項目有很多文件時,要找出控制臺的輸出是在哪里print出來的很麻煩,不過這事對于強大的python來說小菜一碟。
先上代碼和效果,再說明。
?
import sys,traceback class mystdout:stdout = sys.stdoutdef 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的了。
?
總結
以上是生活随笔為你收集整理的飘逸的python - hack输出流便于调试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从零开始学C++之STL(七):剩下5种
- 下一篇: 2013年7月27日杂记