Python3 使用 pigz 压缩目录,实时显示进度
以下是使用 Python3 编写的自定义目录和输出目录,利用 pigz 压缩目录下文件和文件夹并显示实时进度的代码:
import os
import subprocess
import sys
import time
def pigz_compress(source_dir, output_dir):
# 获取源目录下的所有文件和文件夹
all_files = os.listdir(source_dir)
# 遍历所有文件和文件夹
for file in all_files:
# 构造源文件和目标文件的路径
source_path = os.path.join(source_dir, file)
output_path = os.path.join(output_dir, file)
# 判断是文件还是文件夹
if os.path.isfile(source_path):
# 如果是文件,则获取文件名和后缀名
filename, ext = os.path.splitext(file)
# 构造目标文件路径,不包括文件后缀
output_path = os.path.join(output_dir, filename)
# 调用 pigz 命令压缩文件
subprocess.call(['pigz', '-p', '4', '-k', '-c', source_path, '>', output_path + '.gz'])
elif os.path.isdir(source_path):
# 如果是文件夹,则递归调用 pigz_compress 函数
pigz_compress(source_path, output_path + '.tar.gz')
def display_progress(current, total):
# 计算当前进度百分比
progress = int(current / total * 100)
# 构造进度条字符串
bar = '[' + '#' * progress + ' ' * (100 - progress) + ']'
# 输出进度条和百分比
sys.stdout.write('
' + bar + ' ' + str(progress) + '%')
sys.stdout.flush()
if __name__ == '__main__':
# 获取源目录和输出目录
source_dir = input('请输入源目录路径:')
output_dir = input('请输入输出目录路径:')
# 开始压缩
pigz_compress(source_dir, output_dir)
# 输出压缩进度
current = 0
total = len(os.listdir(source_dir))
while current < total:
display_progress(current, total)
current = len(os.listdir(output_dir))
time.sleep(0.1)
display_progress(total, total)
print('
压缩完成!')
使用该代码时,需要先安装 pigz 命令行工具。在 Ubuntu 系统中,可以通过以下命令安装:
sudo apt-get install pigz
在 CentOS 系统中,可以通过以下命令安装:
sudo yum install pigz
使用该代码时,需要输入源目录路径和输出目录路径。程序会将源目录下的所有文件和文件夹压缩到输出目录下,压缩格式为 gzip 和 tar.gz。程序会实时显示压缩进度,直到所有文件和文件夹都压缩完成。
原文地址: https://www.cveoy.top/t/topic/nDeJ 著作权归作者所有。请勿转载和采集!