擅长:python、mysql、java
<p>替换<code>sys.stdout</code>怎么样?你知道吗</p>
<p>例如:</p>
<pre><code>import sys
import traceback
class StacktraceOnPrint:
def __init__(self, orig_stdout, substring):
self.orig_stdout = orig_stdout
self.substring = substring
def write(self, txt):
if self.substring in txt:
traceback.print_stack() # OR import pdb; pdb.set_trace()
self.orig_stdout.write(txt)
sys.stdout = StacktraceOnPrint(sys.stdout, 'blah')
print 'test ...'
print 'Hello blah.'
print 'test ...'
</code></pre>
<p><strong>注意</strong><a href="http://docs.python.org/2/library/traceback.html#traceback.print_stack" rel="nofollow">^{<cd2>}</a>使用<code>sys.stderr</code>。如果您想捕获<code>sys.stderr</code>,请使用不同的函数(如<a href="http://docs.python.org/2/library/traceback.html#traceback.format_stack" rel="nofollow">^{<cd5>}</a>)。否则它将永远重复;导致<code>RuntimeError: maximum recursion depth exceeded</code>。。你知道吗</p>