How to duplicate sys.stdout to a log file?

前端 未结 17 891
醉酒成梦
醉酒成梦 2020-11-22 06:54

Edit: Since it appears that there\'s either no solution, or I\'m doing something so non-standard that nobody knows - I\'ll revise my question to also ask: What is the best w

17条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 07:31

    To complete John T answer: https://stackoverflow.com/a/616686/395687

    I added __enter__ and __exit__ methods to use it as a context manager with the with keyword, which gives this code

    class Tee(object):
        def __init__(self, name, mode):
            self.file = open(name, mode)
            self.stdout = sys.stdout
            sys.stdout = self
    
        def __del__(self):
            sys.stdout = self.stdout
            self.file.close()
    
        def write(self, data):
            self.file.write(data)
            self.stdout.write(data)
    
        def __enter__(self):
            pass
    
        def __exit__(self, _type, _value, _traceback):
            pass
    

    It can then be used as

    with Tee('outfile.log', 'w'):
        print('I am written to both stdout and outfile.log')
    

提交回复
热议问题