python tqdm和日志记录

时间:2018-07-16 19:44:53

标签: python logging multiprocessing tqdm

我有一个Python脚本,用于使用netmiko访问/操纵网络设备。为了加快处理速度,我现在使用tqdm和用于多处理的进程池。

除了记录的东西,这工作正常。记录器对主要对象工作正常,但不适用于tqdm创建的进程。

重要的代码段如下:

def threaded_function(params):
    """the custom function

    :param kwargs params: device details packed as keyword arguments
    :returns: dictionary containing the results of each step
    """

    logging.debug('TEST')
    logging.info('TEST2')
    logging.error('TEST3')



def main_loop():
    logging.getLogger("netmiko").propagate = False
    logging.getLogger("netmiko").disabled = True
    logging.getLogger("paramiko").propagate = False
    logging.getLogger("paramiko").disabled = True

    log_time = datetime.now().strftime("%Y%m%d-%H%M%S")
    LOG_FILE = os.path.basename(input_file) + '.txt'

    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    if args.log2file:
        log_format_file = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        rfh = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1048576, backupCount=10)
        rfh.setLevel(args.filelevel)
        rfh.setFormatter(log_format_file)
        logger.addHandler(rfh)

    if args.log2con:
        log_format_con = logging.Formatter('%(message)s')
        ch = logging.StreamHandler()
        ch.setLevel(args.conlevel)
        ch.setFormatter(log_format_con)
        logger.addHandler(ch)

    if not args.log2file and not args.log2con:
        logger.disabled = True
        logger.propagate = False

    logging.info("JOB STARTED: " + str(log_time))


    pool = multiprocessing.Pool(max_cpu_count)
    with tqdm(total=len(input_list), ascii=True, unit="dev", desc='processing',
              disable=(False if args.log2con else True)) as t:
        for _ in pool.imap_unordered(threaded_function, input_list):
            t.update(1)
            results.append(_)



if __name__ == "__main__":
    main_loop()

有人知道我错了吗?我尝试通过此文档(https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes)的第二个示例传递队列,但是没有运气。

任何帮助表示赞赏 尼克斯

0 个答案:

没有答案