有时需要把print的内容输出到变量储存起来,比如调用别人的脚本,别人结果都是print出来的。有2种办法,第一种是先重定向到文件,再load回来,第二种是直接用一个object的write方法纪录下来,记得最后要重新定向stdout
方法一输出到文件:
temp = sys.stdout sys.stdout = open('.server_all','w') print 1,2,3 # 测试,之后可以检查下.server_all 文件 sys.stdout.close() sys.stdout = temp #resotre print print 1,2,3 # 测试
方法二输出到含有write方法的对象:
class TextArea(object): def __init__(self): self.buffer = [] def write(self, *args, **kwargs): self.buffer.append(args) import sys stdout = sys.stdout sys.stdout = TextArea() # print to TextArea print "testA" print "testB" print "testC" text_area, sys.stdout = sys.stdout, stdout # print to console print text_area.buffer