【问题标题】:Python tarfile: how to use tar+gzip compression with follow symbolic link?Python tarfile:如何使用带有符号链接的 tar+gzip 压缩?
【发布时间】:2017-01-12 06:14:26
【问题描述】:

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

  • tarfile.open() 支持“w:gz”模式但不支持“取消引用”选项
  • 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)
...

【问题讨论】:

    标签: python gzip tar dereference tarfile


    【解决方案1】:

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

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

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

    【讨论】:

    • 有效!谢谢,我阅读了文档,只是没有尝试这种明显的方法。
    猜你喜欢
    • 2012-01-04
    • 2012-09-01
    • 2012-09-24
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 2015-08-30
    相关资源
    最近更新 更多