Python tarfile : how to use tar+gzip compression with follow symbolic link?

标签 python gzip tar dereference tarfile

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

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

最佳答案

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

因此,如果您只是将其作为关键字参数传递,您可以对它们中的任何一个使用解引用:

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

关于Python tarfile : how to use tar+gzip compression with follow symbolic link?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39321031/

相关文章:

python - TPOT P@K 定制记分器

python - cx_Freeze Exe 应用程序一打开就关闭,没有任何错误

c# - HttpClient Gzip 压缩

php - 获取元标记在 php 中不起作用

tomcat - java.io.IOException : unexpected EOF with 512 bytes unread 异常

python - 在没有mixin的情况下迭代类对象的字典 - python

python - 我需要将所有其他数字乘以 3,但不知道我做错了什么

apache-flex - 压缩 swf 文件是否可能导致文件更大?

linux - 如何在使用 tar 压缩目录时排除大文件

python - 如何只提取 .tar.gz 成员的文件?