python stdout 重定向

 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

原文地址:https://www.cnblogs.com/hangj/p/4990719.html