python 学习之输出流重定向
写了一个简单的例子,记录与此。
注:实现输出流的目标类只需要简单的定义一个 write() 方法即可。
import sys
buffer = ''
class Logger:
def write(self, s):
global buffer
buffer += s
mylogger = Logger()
stdout_ = sys.stdout # backup reference to the old stdout.
sys.stdout = mylogger
print 'ok'
print '1'
print {'a': 1, 'b': 2}, 'hello', [1,2,3]
sys.stdout = stdout_
print buffer
buffer = ''
class Logger:
def write(self, s):
global buffer
buffer += s
mylogger = Logger()
stdout_ = sys.stdout # backup reference to the old stdout.
sys.stdout = mylogger
print 'ok'
print '1'
print {'a': 1, 'b': 2}, 'hello', [1,2,3]
sys.stdout = stdout_
print buffer