Журнал Python StreamHandler не отправляет вывод в sys.stdout - PullRequest
1 голос
/ 07 ноября 2019

Мой код Python:

def _init_cmd_logger(self):
    # Init streamer
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(message)s')
    stream_handler.setFormatter(formatter)
    # Configure logger
    cmd_output_logger = logging.getLogger(self._ansible_command)
    cmd_output_logger.propagate = False
    cmd_output_logger.handlers = []
    cmd_output_logger.addHandler(stream_handler)
    return cmd_output_logger

def _live_output_manage(self, popen):
    stdout = []  # Var with std out
    stderr = []  # Var with std err
    # Print outout while executing
    while True:
        reads = [popen.stdout.fileno(), popen.stderr.fileno()]
        ret = select.select(reads, [], [])
        for filed in ret[0]:
            if filed == popen.stdout.fileno():
                read = popen.stdout.readline().strip()
                if read != '':
                    self._cmd_output_logger.info(read)
                    self._logger.debug(read)
                    stdout.append(read)
            if filed == popen.stderr.fileno():
                read = popen.stderr.readline().strip()
                if read != '':
                    self._cmd_output_logger.error(read)
                    self._logger.error(read)
                    stderr.append(read)
        # A None value indicates that the process hasnt terminated yet
        if popen.poll() is not None:
            break
    # A None value indicates that the process has terminated correctly
    return_code = popen.wait()
    return return_code, stdout, stderr

Код работает нормально, пока мы не попытаемся отправить на sys.stdout процесс с более чем 1000 строк. Мы думаем, что у процесса python недостаточно времени для его завершения (записи ввода / вывода) до следующего вызова self._cmd_output_logger.info(read)

Наше решение было вставлено time.sleep(*) после logger.info(). Но мы не уверены в этом вопросе. Или если бы у нас было лучшее решение

...