How to duplicate sys.stdout to a log file?

前端 未结 17 1130
醉酒成梦
醉酒成梦 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:48

    I had this same issue before and found this snippet very useful:

    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 flush(self):
            self.file.flush()
    

    from: http://mail.python.org/pipermail/python-list/2007-May/438106.html

提交回复
热议问题