How to duplicate sys.stdout to a log file?

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

    None of the answers above really seems to answer the problem posed. I know this is an old thread, but I think this problem is a lot simpler than everyone is making it:

    class tee_err(object):
    
     def __init__(self):
        self.errout = sys.stderr
    
        sys.stderr = self
    
        self.log = 'logfile.log'
        log = open(self.log,'w')
        log.close()
    
     def write(self, line):
    
        log = open(self.log,'a')
        log.write(line)
        log.close()   
    
        self.errout.write(line)
    

    Now this will repeat everything to the normal sys.stderr handler and your file. Create another class tee_out for sys.stdout.

提交回复
热议问题