Python tarfile 进度显示
有没有什么库可以在用Python把文件添加到tar压缩包时显示进度?或者说,能不能扩展tarfile模块的功能来做到这一点?
理想情况下,我想显示tar文件创建的整体进度,以及预计完成的时间。
如果有人能提供帮助,那真是太感谢了。
5 个回答
2
我最近写了一个包装库,它可以提供进度回调的功能。你可以在GitHub上看看:
https://github.com/thomaspurchas/tarfile-Progress-Reporter
如果你需要帮助,随时可以问我。
2
找一个可以像文件一样使用的东西,或者自己写一个,这个东西要能包裹真实的文件,并且能提供进度报告。然后把它传给 Tarfile.addfile()
,这样你就能知道有多少字节被请求加入到压缩包里。如果 Tarfile
一下子想要读取整个文件,你可能需要使用或实现一些限制措施,以免一次性读取太多数据。
2
很遗憾,看起来没有简单的方法可以逐字节地获取数字。
你是在往这个tar文件里添加非常大的文件吗?如果不是的话,我建议你可以按文件来更新进度,这样每当有文件被添加到tar文件时,进度就会根据每个文件的大小来更新。
假设你所有的文件名都在一个叫 toadd
的变量里,而 tarfile
是一个 TarFile
对象。那这样做怎么样,
from itertools import imap
from operator import attrgetter
# you may want to change this depending on how you want to update the
# file info for your tarobjs
tarobjs = imap(tarfile.getattrinfo, toadd)
total = sum(imap(attrgetter('size'), tarobjs))
complete = 0.0
for tarobj in tarobjs:
sys.stdout.write("\rPercent Complete: {0:2.0d}%".format(complete))
tarfile.add(tarobj)
complete += tarobj.size / total * 100
sys.stdout.write("\rPercent Complete: {0:2.0d}%\n".format(complete))
sys.stdout.write("Job Done!")