擅长:python、mysql、java
<p>正如查尔斯已经提到的,问题在于缓冲。我在为SNMPd编写一些模块时遇到了类似的问题,并用自动刷新版本替换stdout解决了这个问题。</p>
<p>我使用了以下代码,灵感来自ActiveState上的一些帖子:</p>
<pre><code>class FlushFile(object):
"""Write-only flushing wrapper for file-type objects."""
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
# Replace stdout with an automatically flushing version
sys.stdout = FlushFile(sys.__stdout__)
</code></pre>