How to output to the console and file?

前端 未结 8 1154
青春惊慌失措
青春惊慌失措 2020-11-30 02:54

I\'m trying to find out a way in python to redirect the script execution log to a file as well as stdout in a pythonic way. Is there any easy way of achieving t

相关标签:
8条回答
  • 2020-11-30 03:38

    You should use the logging library, which has this capability built in. You simply add handlers to a logger to determine where to send the output.

    0 讨论(0)
  • 2020-11-30 03:40

    Here's a small improvement that to @UltraInstinct's Tee class, modified to be a context manager and also captures any exceptions.

    import traceback
    import sys
    
    # Context manager that copies stdout and any exceptions to a log file
    class Tee(object):
        def __init__(self, filename):
            self.file = open(filename, 'w')
            self.stdout = sys.stdout
    
        def __enter__(self):
            sys.stdout = self
    
        def __exit__(self, exc_type, exc_value, tb):
            sys.stdout = self.stdout
            if exc_type is not None:
                self.file.write(traceback.format_exc())
            self.file.close()
    
        def write(self, data):
            self.file.write(data)
            self.stdout.write(data)
    
        def flush(self):
            self.file.flush()
            self.stdout.flush()
    

    To use the context manager:

    print("Print")
    with Tee('test.txt'):
        print("Print+Write")
        raise Exception("Test")
    print("Print")
    
    0 讨论(0)
提交回复
热议问题