【问题标题】:How can I suppress the output of file errors when using tqdm?使用 tqdm 时如何抑制文件错误的输出?
【发布时间】:2023-03-14 05:37:02
【问题描述】:

我正在加载一堆文件,并希望使用 tqdm 显示相应的进度条。

for file_path in tqdm(file_paths, position=0, desc='files loaded'):
    if is_binary(file_path):
        continue

    try:    
        with open(file_path, 'r', encoding='utf8', errors='ignore') as input_file:
            file_content = input_file.read()
                    
            processing_queue.put(file_content)
    except FileNotFoundError as e:
        main_logger.error(f'Encountered exception while opening {file_path}: {e}')

即使我正在处理因异常而无法找到的文件,我仍然会收到打印到控制台的错误消息,这会干扰 tqdm 的输出:

files loaded:  99%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▎ | 257398/260429 [6:17:16<07:16,  6.95it/s]
[Errno 2] No such file or directory: '\\\\server\\path\\to\\file'██████                                                                                   | 112570/260429 [6:17:11<7:05:21,  5.79it/s] 
files loaded: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 260429/260429 [6:21:29<00:00, 11.38it/s] 

为什么这些消息仍然打印到控制台,可以采取什么措施来抑制它们?

【问题讨论】:

  • 你的main_logger有StreamHandler,不想在控制台打印的时候只能用FileHandler。
  • @ZavenZareyan main_logger 已经在使用 FileHandler,问题是错误消息仍然打印到控制台。

标签: python exception io tqdm


【解决方案1】:

好的,我先在单独的 try/except 块中打开文件来修复它!

for file_path in tqdm(file_paths, position=0, desc='files loaded'):
    try:
        open(file_path).close()
    except EnvironmentError as e:
        main_logger.error(f'Encountered exception while opening {file_path}: {e}')
        continue


    if is_binary(file_path):
        continue

        
    with open(file_path, 'r', encoding='utf8', errors='ignore') as input_file:
        file_content = input_file.read()
                    
        processing_queue.put(file_content)

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多