2017年7月14日 星期五

Python - Printing to screen and writing to a file at the same time - 將結果同時輸出到console和存到file

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10
  1. import sys
  2. import time
  3. from datetime import datetime
  4. class tee(object):
  5. def __init__(self, *files):
  6. self.files = files
  7. def write(self, obj):
  8. for f in self.files:
  9. f.write(obj)
  10. f.flush() # 如果想要output可以即時可視,若註解需等全部結果跑完才會在console與檔案看見
  11. def flush(self):
  12. pass
  13. log_path = './log-%s.txt' % (datetime.now().strftime('%Y-%m-%dT%H_%M_%S'))
  14. # output only on screen
  15. print('output only on screen:')
  16. print(123)
  17. with open(log_path,'w') as f:
  18. sys.stdout=tee(sys.stdout, f)
  19. # output on both console and file
  20. print('output on both console and file:')
  21. print(456)
  22. time.sleep(5)
執行結果:
``` # 在console可以看到以下結果 output only on screen: 123 output on both console and file: 456 # 在file可以看到以下結果 output on both console and file: 456 ```

沒有留言:

張貼留言