Redirect stdout to a file in Python?

后端 未结 10 1611
轻奢々
轻奢々 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:53

    Based on this answer: https://stackoverflow.com/a/5916874/1060344, here is another way I figured out which I use in one of my projects. For whatever you replace sys.stderr or sys.stdout with, you have to make sure that the replacement complies with file interface, especially if this is something you are doing because stderr/stdout are used in some other library that is not under your control. That library may be using other methods of file object.

    Check out this way where I still let everything go do stderr/stdout (or any file for that matter) and also send the message to a log file using Python's logging facility (but you can really do anything with this):

    class FileToLogInterface(file):
        '''
        Interface to make sure that everytime anything is written to stderr, it is
        also forwarded to a file.
        '''
    
        def __init__(self, *args, **kwargs):
            if 'cfg' not in kwargs:
                raise TypeError('argument cfg is required.')
            else:
                if not isinstance(kwargs['cfg'], config.Config):
                    raise TypeError(
                        'argument cfg should be a valid '
                        'PostSegmentation configuration object i.e. '
                        'postsegmentation.config.Config')
            self._cfg = kwargs['cfg']
            kwargs.pop('cfg')
    
            self._logger = logging.getlogger('access_log')
    
            super(FileToLogInterface, self).__init__(*args, **kwargs)
    
        def write(self, msg):
            super(FileToLogInterface, self).write(msg)
            self._logger.info(msg)
    

提交回复
热议问题