1.方式1
__file__ = open(r‘log.txt‘, ‘a‘) print >>__file__, "hello, world!" __file__.close()
2.方式2
__stdout__ = sys.stdout sys.stdout = open(r‘log.txt‘, ‘a‘) print "hello, world!" sys.stdout.close() sys.stdout = __stdout__
3.方式3
#-*- coding:utf8 -*- import sys class stdout: def __init__(self): self.buff = [] self.__file__ = open(r‘log.txt‘, ‘a‘) self.__stdout__ = sys.stdout def write(self, s): self.buff.append(s) self.__file__.write(s) self.__file__.flush() self.__stdout__.write(s) def flush(self): self.buff = [] self.__stdout__.flush() def close(self): self.__file__.close() def reset(self): sys.stdout = self.__stdout__ if __name__ == ‘__main__‘: sys.stdout = stdout() for i in xrange(10): print "hello, world!" sys.stdout.close() #sys.stdout.__file__.close() sys.stdout.reset() #sys.stdout = sys.stdout.__stdout__ print "im back!"
时间: 2024-10-11 07:45:13