我有一个用于使用 netmiko 访问/操作网络设备的 python 脚本。为了加快处理速度,我现在使用 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)但没有运气..
任何帮助表示赞赏 regs nick