gpt4 book ai didi

Python tarfile 进度输出?

转载 作者:太空狗 更新时间:2023-10-29 17:15:24 26 4
gpt4 key购买 nike

我正在使用以下代码提取一个 tar 文件:

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

但是,我想密切关注目前正在提取哪些文件的进度。我该怎么做?

额外奖励积分:是否也可以创建一定比例的提取过程?我想用它来让 tkinter 更新进度条。谢谢!

最佳答案

文件进度和全局进度:

import io
import os
import tarfile

def get_file_progress_file_object_class(on_progress):
class FileProgressFileObject(tarfile.ExFileObject):
def read(self, size, *args):
on_progress(self.name, self.position, self.size)
return tarfile.ExFileObject.read(self, size, *args)
return FileProgressFileObject

class TestFileProgressFileObject(tarfile.ExFileObject):
def read(self, size, *args):
on_progress(self.name, self.position, self.size)
return tarfile.ExFileObject.read(self, size, *args)

class ProgressFileObject(io.FileIO):
def __init__(self, path, *args, **kwargs):
self._total_size = os.path.getsize(path)
io.FileIO.__init__(self, path, *args, **kwargs)

def read(self, size):
print("Overall process: %d of %d" %(self.tell(), self._total_size))
return io.FileIO.read(self, size)

def on_progress(filename, position, total_size):
print("%s: %d of %s" %(filename, position, total_size))

tarfile.TarFile.fileobject = get_file_progress_file_object_class(on_progress)
tar = tarfile.open(fileobj=ProgressFileObject("a.tgz"))
tar.extractall()
tar.close()

关于Python tarfile 进度输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3667865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com