Python tarfile:如何使用跟随符号链接的tar + gzip压缩?

时间:2016-09-04 20:07:29

标签: python gzip tar dereference tarfile

我如何使用"使用tar + gzip压缩符合符号链接" Python 3.4中的功能?问题是:

  • tarfile.open()支持" w:gz"模式,但不支持" dereference"选项
  • tarfile.tarfile()支持" dereference"但不支持" w:gz"模式

代码:

...
mode = ""
if bckentry['method'] == "tar":
    mode = "w"
elif bckentry['method'] == "targz":
    mode = "w:gz"

archive = tarfile.TarFile(name=filepath, mode=mode)
archive.dereference = True if bckentry['followsym'] == "yes" else False
# archive = tarfile.open(filepath, mode=mode)

if bckentry['withpath'] == 'yes':
    for entry in bckentry['include_dirs']:
        archive.add(entry, filter=self.filter_tar)
elif bckentry['withpath'] == 'no':
    for entry in bckentry['include_dirs']:
        archive.add(entry, arcname=os.path.basename(entry), filter=self.filter_tar)
...

1 个答案:

答案 0 :(得分:2)

tarfile.openTarFile.open类方法的快捷方式,后者又调用TarFile构造函数。文档有点模糊,但从代码中可以明显看出前两个将dereference关键字参数和所有其他未消耗的kwargs传递给TarFile构造函数。

因此,如果您只是将其作为关键字参数传递,则可以将dereference与其中任何一个一起使用:

archive = tarfile.open(name='foo.tar.gz', mode='w:gz', dereference=True)