| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- """
- An handler for the stdout and the stderr output
- @author: olivier.massot, 05-2020
- """
- import logging
- import os
- import threading
- class PipeHandler(threading.Thread):
- """ Handle the stdout/stderr output from a Popen object """
- def __init__(self, logger_name, default_level=logging.INFO):
- """ Setup the object with a logger and a loglevel
- and start the thread
- """
- threading.Thread.__init__(self)
- self.daemon = False
- self.fdRead, self.fdWrite = os.pipe()
- self.pipeReader = os.fdopen(self.fdRead, encoding='utf-8')
- self.start()
- self.logger = logging.getLogger(logger_name)
- self.default_level = default_level
- def fileno(self):
- """ Return the write file descriptor of the pipe
- """
- return self.fdWrite
- def process(self, line):
- """ Process the last line that was read
- """
- self.logger.log(self.default_level, line)
- def run(self):
- """ Run the thread, logging everything.
- """
- try:
- for line in iter(self.pipeReader.readline, ''):
- self.process(line.strip('\n'))
- except UnicodeDecodeError:
- self.process(' -- Error while decoding the incoming, unable to log --')
- finally:
- self.pipeReader.close()
- def close(self):
- """ Close the write end of the pipe.
- """
- os.close(self.fdWrite)
|