Python tar文件:如何使用 tar+gzip 压缩和 follow symbolic link?
Python tarfile: how to use tar+gzip compression with follow symbolic link?
如何在 Python 3.4 中使用 tar+gzip 压缩和 "follow symbolic link" 功能?问题是:
- 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)
...
tarfile.open
is a shortcut for the TarFile.open
classmethod, that in turn calls the TarFile
构造函数。文档有点模糊,但从代码中可以明显看出前两个将 dereference
关键字参数和所有其他未使用的 kwargs 传递给 TarFile
构造函数。
因此,您可以将 dereference
与它们中的任何一个一起使用,如果您只是将其作为关键字参数传递:
archive = tarfile.open(name='foo.tar.gz', mode='w:gz', dereference=True)
如何在 Python 3.4 中使用 tar+gzip 压缩和 "follow symbolic link" 功能?问题是:
- 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)
...
tarfile.open
is a shortcut for the TarFile.open
classmethod, that in turn calls the TarFile
构造函数。文档有点模糊,但从代码中可以明显看出前两个将 dereference
关键字参数和所有其他未使用的 kwargs 传递给 TarFile
构造函数。
因此,您可以将 dereference
与它们中的任何一个一起使用,如果您只是将其作为关键字参数传递:
archive = tarfile.open(name='foo.tar.gz', mode='w:gz', dereference=True)