75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
import os
|
|
import time
|
|
|
|
from py7zr import py7zr
|
|
from py7zr.callbacks import ExtractCallback
|
|
|
|
from launcher.file.utils import format_size
|
|
from launcher.webview.events import custom_event
|
|
|
|
|
|
class MyExtractCallback(ExtractCallback):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.total_size = 0
|
|
self.last_print_time = time.time()
|
|
|
|
def report_start(self, archive_name, archive_format):
|
|
pass
|
|
|
|
def report_start_preparation(self):
|
|
pass
|
|
|
|
def report_end(self, processing_file_path, wrote_bytes):
|
|
self.total_size += int(wrote_bytes)
|
|
current_time = time.time()
|
|
if current_time - self.last_print_time >= 1.0: # 至少每隔1秒输出一次
|
|
custom_event(f"已解压: {format_size(self.total_size)}")
|
|
self.last_print_time = current_time
|
|
|
|
def report_postprocess(self):
|
|
pass
|
|
|
|
def report_update(self, message):
|
|
pass
|
|
|
|
def report_warning(self, message):
|
|
pass
|
|
|
|
|
|
def extract_7z_file(file_name, file_path, destination_folder, delete_after_extract=True):
|
|
"""
|
|
解压7z文件到指定文件夹
|
|
:param file_name: 7z文件的名称
|
|
:param file_path: 7z文件的路径
|
|
:param destination_folder: 解压目标文件夹
|
|
:param delete_after_extract: 解压后删除压缩文件,默认删除
|
|
:return: 解压是否成功
|
|
"""
|
|
if not os.path.exists(destination_folder):
|
|
os.makedirs(destination_folder)
|
|
|
|
custom_event(f"开始解压文件: {file_name}")
|
|
try:
|
|
start_time = time.time()
|
|
with py7zr.SevenZipFile(file_path, mode='r') as z:
|
|
callback = MyExtractCallback()
|
|
z.extractall(path=destination_folder, callback=callback)
|
|
end_time = time.time()
|
|
total_elapsed_time = end_time - start_time
|
|
formatted_total_elapsed_time = f"{total_elapsed_time:.2f} 秒"
|
|
custom_event(
|
|
f"解压完成: {file_name}, 总大小: {format_size(callback.total_size)}, 耗时: {formatted_total_elapsed_time}")
|
|
except Exception as e:
|
|
e.print_exc()
|
|
custom_event(f"解压失败: {str(e)}")
|
|
return False
|
|
|
|
if delete_after_extract:
|
|
try:
|
|
os.remove(file_path)
|
|
custom_event(f"删除{file_path}成功")
|
|
except OSError as e:
|
|
custom_event(f"删除{file_path}失败: {str(e)}")
|
|
|
|
return True
|