python print重定向到文件

来源:互联网 发布:suse linux 挂载iso 编辑:程序博客网 时间:2024/04/30 17:40

python print重定向到文件

  我们在开发中,有时需要将log信息保存到文件中,方便后续的查看,而无论是python2的print 还是python3的print(),默认都是将信息输出的控制台中,无法保存到本地,因此需要进行重定向。
  
import timeimport osclass LOG():    def __init__(self):        if not os.path.exists('log'):            os.mkdir('log')        self.log = open('log/%s.txt' % time.strftime("%Y_%m_%d_%I_%M_%S"), 'w+')        log_fils = os.listdir('log/')        log_fils.sort()        if len(log_fils)>200:            print('log file >200,delere old file',log_fils.pop(0),file=self.log)    def Info(self,*data):        msg=time.strftime("%Y-%m-%d_%I:%M:%S")+" INFO:"        for info in data:            if type(info) == int:                msg=msg+str(info)            else:                msg=msg+ str(info)        print (msg)        # print >>self.log,msg        print(msg,file=self.log)    def Warn(self,*data):        msg=time.strftime("%Y-%M-%d_%I:%M:%S")+" WARN:"        for info in data:            if type(info) == int:                msg = msg+str(info)            else:                msg = msg+ info        # print >> self.log, msg        print(msg, file=self.log)        print (msg)    def Error(self, *data):        msg = time.strftime("%Y-%M-%d_%I:%M:%S") + " ERROR:"        for info in data:            if type(info) == int:                msg = msg + str(info)            else:                msg = msg + info        # print >> self.log, msg        print(msg, file=self.log)        print(msg)


  如上面的黄色标准:
 print >> self.log, msg    #python2 print(msg, file=self.log) #python3