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

4

我该如何在Python 3.4中使用带有“跟随符号链接”功能的tar+gzip压缩?问题是:

  • 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个回答

6

tarfile.openTarFile.open类方法的快捷方式,该方法又调用TarFile构造函数。虽然文档有点模糊,但从代码中可以看出,前两个方法将通过dereference关键字参数并传递所有其他未使用的kwargs到TarFile构造函数。

因此,您只需将dereference作为关键字参数传递,即可在任何方法中使用它:

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

它起作用了!谢谢,我阅读了文档,只是没有尝试这个明显的方法。 - Balint

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接