Python脚本需要很长时间来备份文件夹

我从一些书中复制了这个脚本来做一些文件夹的tar.bz2来备份

#!/usr/bin/env python import tarfile, os def make_tar(folder_to_backup, dest_folder, compression='bz2'): if compression: dest_ext ='.' + compression else: dest_ext = '' arcname = os.path.basename(folder_to_backup) dest_name = '%s.tar%s' % (arcname, dest_ext) dest_path = os.path.join(dest_folder, dest_name) if compression: dest_cmp = ':' + compression else: dest_cmp = '' out = tarfile.TarFile.open(dest_path, 'w' +dest_cmp) out.add(folder_to_backup, arcname) out.close() return dest_path print "Doing Python" make_tar('/home/bob/public_html','/home/bob/testbck', compression='bz2') 

现在bash需要40秒来备份该文件夹,python大约需要8分钟。

我在哪里错了,或者python对于这些任务总是比较慢

我复制/粘贴你的代码,并分别与tar cjpftar czpf两个bz2gz尝试,发现他们执行相同的。 你正在使用哪个版本的Python? /home/bob/public_html上有多less个文件? 你是否先尝试了tar命令,然后是你的脚本或者其他方法? (我猜文件caching可能会歪曲结果一点,但不是太多,但)。

我只是看了一下TarFile的实现。 顺便说一下, ipython很容易:

 import tarfile %edit tarfile.TarFile.add 

这是目录的情况:

  elif tarinfo.isdir(): self.addfile(tarinfo) if recursive: for f in os.listdir(name): self.add(os.path.join(name, f), os.path.join(arcname, f), recursive, exclude) 

随着文件总数的增加,我可以看到越来越慢。 我猜测tar可能会更好地处理这种情况下。 不过这只是一个猜测。