在代码中,进度条的信息是通过tqdm库生成的,其中包括已用时、剩余时间和速度等信息。但是在使用subprocess运行pigz压缩文件时,并没有更新进度条的信息,导致进度条上的信息不正确。

解决方法是在subprocess运行pigz时,使用stdout参数将压缩后的数据输出到一个临时文件中,然后再读取该文件的大小,从而更新进度条的信息。修改后的代码如下:

import os import subprocess from tqdm import tqdm

def pack_files(source_dir, output_dir): # 检查源目录和输出目录是否存在 if not os.path.exists(source_dir) or not os.path.isdir(source_dir): print(f'源目录{source_dir}不存在或不是一个目录') return

if not os.path.exists(output_dir) or not os.path.isdir(output_dir):
    print(f'输出目录{output_dir}不存在或不是一个目录')
    return

# 计算文件总数
total_files = sum([len(files) for root, dirs, files in os.walk(source_dir)])

# 外层进度条(总进度)
with tqdm(total=total_files, desc='压缩进度', bar_format='{desc}:{percentage:3.0f}%|\033[0m\033[32m{bar}\033[0m| [已用时:{elapsed} 剩余时间:{remaining} 速度:{rate_fmt}]') as pbar:
    for root, dirs, files in os.walk(source_dir):
        for file in files:
            # 获取需要压缩的文件路径
            file_path = os.path.join(root, file)
            
            # 获取文件名和文件后缀
            file_name, file_ext = os.path.splitext(file)
            
            # 拼接输出文件路径(去掉文件后缀)
            output_file = os.path.join(output_dir, f'{file_name}.gz')
            
            # 使用pigz进行压缩,并将压缩后的数据输出到临时文件
            with open(output_file+'.tmp', 'wb') as tmp_file:
                subprocess.run(['pigz', '-c', file_path], stdout=tmp_file)
            
            # 计算压缩后的文件大小
            compressed_size = os.path.getsize(output_file+'.tmp')
            
            # 将临时文件重命名为正式的压缩文件
            os.rename(output_file+'.tmp', output_file)
            
            # 更新外层进度条
            pbar.update(1)
            pbar.set_postfix({'已用时': pbar.format_interval(pbar.elapsed), 
                              '剩余时间': pbar.format_interval(pbar.eta), 
                              '速度': pbar.format_dict(pbar.format_dict({'rate': pbar.rate, 'unit': 'files/s'})),
                              '压缩大小': pbar.format_sizeof(compressed_size)})
            
            # 输出信息到控制台
            tqdm.write(f'已将文件{file_path}压缩到{output_file}')

路径

source_dir = '/home/115/up' output_dir = '/home/115/app' pack_files(source_dir, output_dir

代码中的已用时、剩余时间、速度压缩文件时不更新import osimport subprocessfrom tqdm import tqdmdef pack_filessource_dir output_dir # 检查源目录和输出目录是否存在 if not ospathexistssource_dir or not ospathisdirsource_dir print

原文地址: http://www.cveoy.top/t/topic/c4HM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录