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
import sys
import time
from datetime import datetime
class tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)
            f.flush() # 如果想要output可以即時可視,若註解需等全部結果跑完才會在console與檔案看見
    def flush(self):
        pass
log_path =  './log-%s.txt' % (datetime.now().strftime('%Y-%m-%dT%H_%M_%S'))

# output only on screen
print('output only on screen:')
print(123)
with open(log_path,'w') as f:
    sys.stdout=tee(sys.stdout, f)
    # output on both console and file
    print('output on both console and file:')
    print(456)
    time.sleep(5)
執行結果:
``` # 在console可以看到以下結果 output only on screen: 123 output on both console and file: 456 # 在file可以看到以下結果 output on both console and file: 456 ```

沒有留言:

張貼留言