本文介绍了Python tarfile 进度输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码提取 tar 文件:
I'm using the following code to extract a tar file:
import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()
但是,我想以目前正在提取的文件的形式密切关注进度.我该怎么做?
However, I'd like to keep tabs on the progress in the form of which files are being extracted at the moment. How can I do this?
额外奖励积分:是否也可以创建一定比例的提取过程?我想将它用于 tkinter 来更新进度条.谢谢!
EXTRA BONUS POINTS: is it possible to create a percentage of the extraction process as well? I'd like to use that for tkinter to update a progress bar. Thanks!
推荐答案
文件进度和全局进度:
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 进度输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!