Files
controller-wisetopdataserver/python/biopro/util/archive.py
T
2021-12-20 14:52:55 +08:00

79 lines
1.9 KiB
Python

"""archive file.
Main
----
options
~~~~~~~
::
./RaspBerryPi3/python/biopro/util/archive.py OUTPUT FILE ...
arguments:
OUTPUT output file path
FILE input file path
output file type
zip Zip archive data
gz gzip compressed data
xz XZ compressed data
Function
--------
"""
import tarfile
import zipfile
from pathlib import Path
from typing import Union
__all__ = ['archive_zip', 'archive_tar_gz', 'archive_tar_xz']
def archive_zip(output_path: Union[str, Path], *filepath: str):
with zipfile.ZipFile(output_path, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=8) as zip_file:
for f in filepath:
name = Path(f).name
zip_file.write(f, arcname=name)
def archive_tar_gz(output_path: Union[str, Path], *filepath: str):
with tarfile.open(output_path, 'w:gz') as tar:
for f in filepath:
name = Path(f).name
tar.add(f, arcname=name)
def archive_tar_xz(output_path: Union[str, Path], *filepath: str):
with tarfile.open(output_path, 'w:xz') as tar:
for f in filepath:
name = Path(f).name
tar.add(f, arcname=name)
if __name__ == '__main__':
import sys
from biopro.util.text import part_suffix
if len(sys.argv) == 1:
print(sys.argv[0], 'OUTPUT', 'FILE ...')
exit(0)
_output_path = sys.argv[1]
_source_path = sys.argv[2:]
_, ftype = part_suffix(_output_path, '.', from_right=True)
if ftype is None:
raise ValueError('undetermined archive file type : ' + _output_path)
if ftype == 'zip':
archive_zip(_output_path, *_source_path)
elif ftype in ('gz', 'tar.gz'):
archive_tar_gz(_output_path, *_source_path)
elif ftype in ('xz', 'tar.xz'):
archive_tar_xz(_output_path, *_source_path)
else:
raise RuntimeError('unsupported archive file type : ' + ftype)