UnzipAndRemove.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import multiprocessing
  2. import traceback
  3. from os import *
  4. from etl.common.PathsAndTable import PathsAndTable
  5. from service.trans_conf_service import update_trans_transfer_progress
  6. from utils.file.trans_methods import read_files, read_excel_files, copy_to_new, split_array
  7. from utils.log.trans_log import trans_print
  8. from utils.systeminfo.sysinfo import get_available_cpu_count_with_percent
  9. from utils.zip.unzip import unzip, unrar, get_desc_path
  10. class UnzipAndRemove(object):
  11. def __init__(self, pathsAndTable: PathsAndTable, filter_types=None):
  12. self.pathsAndTable = pathsAndTable
  13. self.filter_types = filter_types
  14. def get_and_remove(self, file):
  15. to_path = self.pathsAndTable.get_excel_tmp_path()
  16. if str(file).endswith("zip"):
  17. if str(file).endswith("csv.zip"):
  18. copy_to_new(file, file.replace(self.pathsAndTable.read_dir, to_path).replace("csv.zip", 'csv.gz'))
  19. else:
  20. desc_path = file.replace(self.pathsAndTable.read_dir, to_path)
  21. unzip(file, get_desc_path(desc_path))
  22. self.pathsAndTable.has_zip = True
  23. elif str(file).endswith("rar"):
  24. desc_path = file.replace(self.pathsAndTable.read_dir, to_path)
  25. is_success, e = unrar(file, get_desc_path(desc_path))
  26. self.pathsAndTable.has_zip = True
  27. if not is_success:
  28. trans_print(traceback.format_exc())
  29. pass
  30. else:
  31. copy_to_new(file, file.replace(self.pathsAndTable.read_dir, to_path))
  32. def remove_file_to_tmp_path(self):
  33. # 读取文件
  34. try:
  35. if path.isfile(self.pathsAndTable.read_dir):
  36. all_files = [self.pathsAndTable.read_dir]
  37. else:
  38. all_files = read_files(self.pathsAndTable.read_dir)
  39. # 最大取系统cpu的 三分之二
  40. split_count = get_available_cpu_count_with_percent(2 / 3)
  41. all_arrays = split_array(all_files, split_count)
  42. for index, arr in enumerate(all_arrays):
  43. pool_count = split_count if split_count < len(arr) else len(arr)
  44. with multiprocessing.Pool(pool_count) as pool:
  45. pool.starmap(self.get_and_remove, [(i,) for i in arr])
  46. update_trans_transfer_progress(self.pathsAndTable.id,
  47. round(5 + 15 * (index + 1) / len(all_arrays), 2),
  48. self.pathsAndTable.save_db)
  49. all_files = read_excel_files(self.pathsAndTable.get_excel_tmp_path())
  50. trans_print('读取文件数量:', len(all_files))
  51. except Exception as e:
  52. trans_print(traceback.format_exc())
  53. message = "读取文件列表错误:" + self.pathsAndTable.read_dir + ",系统返回错误:" + str(e)
  54. raise ValueError(message)
  55. return all_files
  56. def run(self):
  57. self.remove_file_to_tmp_path()
  58. update_trans_transfer_progress(self.pathsAndTable.id, 20,
  59. self.pathsAndTable.save_db)