# coding: utf-8 import os import sys import tarfile import zipfile import re import platform def get_pkgname(tar_name): ends = ['.tar.gz', '.tar', '.gz', '.gz2', '.bz', '.bz2', '-win32.zip', '-x86.zip', '-bin.zip', '.zip','.exe'] for end in ends: if tar_name.endswith(end): return tar_name.rstrip(end) def unpack_tar(filename, destpath, path=None, get_name=False, fix_path=None): u""" 解壓包,若windows,默認解壓zip格式的壓縮包:壓縮包內不能有根目錄,不然調用後要存放的文件夾下會又有一個文件夾 調用方式unzipFile(包路徑, 要存放的文件夾名) :param filename: 壓縮包位置,絕對路徑 :param destpath: 解壓目錄。絕對路徑 :param path: 解壓後的目錄名稱(windows環境必須輸入) :param get_name: :param fix_path: :return: """ if not os.path.exists(filename): return False if not os.path.exists(destpath): os.mkdir(destpath, 0777) if not sys.platform.startswith('win'): t = tarfile.open(filename) files = t.getnames() dir_lists = [] for i in files: if os.sep in i: dirname = i.split('/')[0] if dirname not in dir_lists: dir_lists.append(i.split('/')[0]) # 爲1代表只有一個主目錄 if len(dir_lists) == 1: untar_path = os.path.join(destpath, dir_lists[0]) t.extractall(path=destpath) else: untar_path = os.path.join(destpath, path) t.extractall(path=untar_path) return untar_path else: dir_name = None zfobj = zipfile.ZipFile(filename) if get_name: for obj_name in zfobj.namelist(): if obj_name.endswith('/') and obj_name.count('/') == 1: dir_name = obj_name.split('/')[0] break # destpath爲C:時,不加分隔符會直接拼接 if destpath.endswith(':'): destpath = destpath + os.sep if fix_path: destpath = os.path.join(destpath, fix_path) zfobj.extractall(path=destpath) zfobj.close() if dir_name: return dir_name else: return True def install_pkgs(package, baseDir): sys_type = platform.architecture()[0] package_name = '' for package_item in package: # 若不存在已解壓的包,進行解壓 package_name = get_pkgname(re.split(r'\\|/', package_item)[-1]) if sys_type == '64bit' and '-x86' in package_name or \ sys_type == '32bit' and '-x64' in package_name: return False, '包類型與系統類型不符' pkg_path = os.path.join(baseDir, package_name) if not os.path.exists(pkg_path): try: package_name = unpack_tar(package_item, baseDir, get_name=True) if isinstance(package_name, bool): package_name = get_pkgname(re.split(r'\\|/', package_item)[-1]) except Exception as e: if 'Permission denied' in '{}'.format(e): return False, u'文件操做失敗,請查看文件是否已存在或沒有相應權限' return True, package_name def unpack_name(filename): return unpack_tar(filename, '/opt', get_name=True)