UnzipAndRemove.py 3.1 KB

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