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

posted on 2015-11-24 10:30  明天有风吹  阅读(709)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园