我已经编写了以下脚本,它允许我将src(可以是单个文件或目录)压缩到目标'dst':#!/usr/bin/env python2
import tarfile
from ntpath import basename, dirname
from os import path, listdir, makedirs, chdir
import errno
import sys
class Archivator:
@staticmethod
def compress(src='input/test', dst='output'):
# if not path.isfile(src_file):
# print('Expecting absolute path to file (not directory) as "src". If "src" does contain a file, the file does not exist')
# return False
if not path.isdir(dst):
return False
# try:
# makedirs(dst_dir)
# except OSError as err:
# if err.errno != errno.EEXIST:
# return False
filename = basename(src) if path.isdir(src) else src
tar_file = dst + '/' + filename + '.tar.gz'
print(tar_file)
print(src)
with tarfile.open(tar_file, 'w:gz') as tar:
print('Creating archive "' + tar_file + '"')
# chdir(dirname(dst_dir))
recr = path.isdir(src)
if recr:
print('Source is a directory. Will compress all contents using recursion')
tar.add(src, recursive=recr)
return True
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Uses tar to compress file')
parser.add_argument('-src', '--source', type=str,
help='Absolute path to file (not directory) that will be compressed')
parser.add_argument('-dst', '--destination', type=str, default='output/',
help='Path to output directory. Create archive inside the directory will have the same name as value of "--src" argument')
# Generate configuration
config = parser.parse_args()
Archivator.compress(config.source, config.destination)
对于单个文件,到目前为止我还没有遇到问题。然而,尽管src(作为一个目录)的压缩确实有效(递归和所有),但我注意到一个非常恼人的问题,即完整的目录结构被复制到tar.gz归档文件中。在
示例:
假设我有以下文件结构:
^{pr2}$
使用src = 'updates/package1'和{}我希望得到的归档文件将放在dst内(这行得通)
包含file1和file2
关于第二点./
|---compression.py (script above)
|
|---updates/
| |
| |---package1/
| |
| |---file1
| |---file2
| |---dir/
| |
| |---file3
|
|---compressed/
|
|---package1.tar.gz
|
|---file1
|---file2
|---dir/
|
|---file3
但是我得到了./
|---compression.py (script above)
|
|---updates/
| |
| |---package1/
| |
| |---file1
| |---file2
| |---dir/
| |
| |---file3
|
|---compressed/
|
|---package1.tar.gz
|
|---updates/
|
|---package1/
|
|---file1
|---file2
|---dir/
|
|---file3
我可能无法找到解决方案。我甚至在src(如果是一个目录)中尝试了chdir-ing,但是没有成功。我的一些实验甚至导致了OSError(由于缺少它应该存在的目录)和一个损坏的存档。在