写了一个简单的例子,记录与此。
注:实现输出流的目标类只需要简单的定义一个 write() 方法即可。

python 学习之输出流重定向import sys
python 学习之输出流重定向
python 学习之输出流重定向buffer 
= ''
python 学习之输出流重定向
python 学习之输出流重定向
class Logger:
python 学习之输出流重定向    
def write(self, s):
python 学习之输出流重定向        
global buffer
python 学习之输出流重定向        buffer 
+= s
python 学习之输出流重定向
python 学习之输出流重定向mylogger 
= Logger()
python 学习之输出流重定向stdout_ 
= sys.stdout # backup reference to the old stdout.
python 学习之输出流重定向
sys.stdout = mylogger
python 学习之输出流重定向
python 学习之输出流重定向
print 'ok'
python 学习之输出流重定向
print '1'
python 学习之输出流重定向
print {'a'1'b'2}, 'hello', [1,2,3]
python 学习之输出流重定向
python 学习之输出流重定向sys.stdout 
= stdout_
python 学习之输出流重定向
print buffer
python 学习之输出流重定向

相关文章:

  • 2021-11-02
  • 2022-12-23
  • 2021-10-14
  • 2021-12-05
  • 2021-03-31
  • 2022-12-23
  • 2021-12-04
猜你喜欢
  • 2021-10-18
  • 2021-05-22
  • 2022-12-23
  • 2022-01-15
  • 2022-12-23
  • 2021-04-01
相关资源
相似解决方案