Redirect stdout to a file in Python?

后端 未结 10 1348
轻奢々
轻奢々 2020-11-21 05:26

How do I redirect stdout to an arbitrary file in Python?

When a long-running Python script (e.g, web application) is started from within the ssh session and backgoun

10条回答
  •  执念已碎
    2020-11-21 05:39

    Here is a variation of Yuda Prawira answer:

    • implement flush() and all the file attributes
    • write it as a contextmanager
    • capture stderr also

    .

    import contextlib, sys
    
    @contextlib.contextmanager
    def log_print(file):
        # capture all outputs to a log file while still printing it
        class Logger:
            def __init__(self, file):
                self.terminal = sys.stdout
                self.log = file
    
            def write(self, message):
                self.terminal.write(message)
                self.log.write(message)
    
            def __getattr__(self, attr):
                return getattr(self.terminal, attr)
    
        logger = Logger(file)
    
        _stdout = sys.stdout
        _stderr = sys.stderr
        sys.stdout = logger
        sys.stderr = logger
        try:
            yield logger.log
        finally:
            sys.stdout = _stdout
            sys.stderr = _stderr
    
    
    with log_print(open('mylogfile.log', 'w')):
        print('hello world')
        print('hello world on stderr', file=sys.stderr)
    
    # you can capture the output to a string with:
    # with log_print(io.StringIO()) as log:
    #   ....
    #   print('[captured output]', log.getvalue())
    

提交回复
热议问题