使print既打印到终端,又写入文件

 1 class Tee(object):
 2     def __init__(self,*files):
 3         self.files = files
 4     def write(self,obj):
 5         for f in self.files:
 6             f.write(obj)
 7 
 8 if __name__ == '__main__':
 9     logname = './new_file.txt'
10     with open(logname,'w') as logfile:
11       original = sys.stdout
12       sys.stdout = Tee(sys.stdout,logfile)
13       // test
14       print '*********************'
15       print 'Well Done!'
16       sys.stdout = original

 

相关文章:

  • 2022-02-19
  • 2022-12-23
  • 2021-10-04
  • 2022-02-18
猜你喜欢
  • 2022-12-23
  • 2021-10-14
  • 2021-12-05
  • 2021-12-04
  • 2021-12-25
  • 2021-09-04
相关资源
相似解决方案