1 import sys
 2 
 3 class Buffer(object):
 4     def __init__(self):
 5         self.buffer = []
 6 
 7     def write(self, *args, **kwargs):
 8         self.buffer.append(args)
 9 
10 def test():
11     stdout = sys.stdout
12     sys.stdout = open('hello_stdout', 'wb')
13 
14     print 'test'
15 
16     sys.stdout.close()
17     sys.stdout = stdout
18 
19 
20     stdout = sys.stdout
21     sys.stdout = Buffer()
22 
23     print 'buffer1'
24     print 'buffer2'
25 
26     buff, sys.stdout = sys.stdout, stdout
27     print buff.buffer
28 
29 if __name__ == '__main__':
30     test()

 跟 decorator 用在一起会比较有趣

https://www.cnblogs.com/hangj/p/4986970.html

 

 

https://stackoverflow.com/questions/7664788/freopen-stdout-and-console

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
  • 2021-10-09
  • 2022-12-23
  • 2022-01-09
  • 2021-06-06
猜你喜欢
  • 2021-05-27
  • 2021-08-09
  • 2021-07-22
  • 2022-12-23
  • 2021-08-08
  • 2021-11-24
相关资源
相似解决方案