如何在 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.open
是 TarFile.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/