How to duplicate sys.stdout to a log file?

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

    The print statement will call the write() method of any object you assign to sys.stdout.

    I would spin up a small class to write to two places at once...

    import sys
    
    class Logger(object):
        def __init__(self):
            self.terminal = sys.stdout
            self.log = open("log.dat", "a")
    
        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)  
    
    sys.stdout = Logger()
    

    Now the print statement will both echo to the screen and append to your log file:

    # prints "1 2" to  AND log.dat
    print "%d %d" % (1,2)
    

    This is obviously quick-and-dirty. Some notes:

    • You probably ought to parametize the log filename.
    • You should probably revert sys.stdout to if you won't be logging for the duration of the program.
    • You may want the ability to write to multiple log files at once, or handle different log levels, etc.

    These are all straightforward enough that I'm comfortable leaving them as exercises for the reader. The key insight here is that print just calls a "file-like object" that's assigned to sys.stdout.

提交回复
热议问题