Python3 多线程批量对所有 gitlab 项目删除 target 目录
当需要同时维护很多项目时,每个项目的 target 必定占用大量的磁盘空间,需要清理时一个个执行 mvn clean 的过程显然不是明智之举。
所以使用一个小工具,来指定一个顶层项目文件夹,来进行递归查找 target 目录,有则自动程序清理,无则跳过,会非常方便。
#!/usr/bin/python3 # -*- coding: UTF-8 -*- import os import os.path import sys import time import functools import logging import threading from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED # 日志 _root_file_path = os.path.abspath(".") _py_filename = os.path.basename(sys.argv[0]).split(".")[0] _log_file = '{}/logs/{}.log'.format(_root_file_path, _py_filename) logging.basicConfig(filename=_log_file, filemode='w', format='%(message)s', level=logging.INFO) console_handler = logging.StreamHandler() console_handler.setLevel('INFO') logging.getLogger().addHandler(console_handler) # 所有目录 paths = [] def time_me(info='耗时'): def _time_me(fn): @functools.wraps(fn) def _wrapper(*args, **kwargs): start = time.perf_counter() fn(*args, **kwargs) print('{} {} {}'.format(fn.__name__, info, int(time.perf_counter() - start)), ' 秒') return _wrapper return _time_me def get_dir(path): file_list = os.listdir(path) try: for tmp in file_list: path_tmp = os.path.join(path, tmp) if os.path.isdir(path_tmp): if not path_tmp.endswith('/target'): get_dir(path_tmp) else: paths.append(path_tmp) # logging.info(path_tmp) except PermissionError: pass def rm_target(_path: str): try: command = 'rm -rf {}'.format(_path) f = os.popen(command) print(f.readline()) logging.info('{} [{}] 完毕'.format(threading.currentThread().getName(), command)) except Exception as e: logging.error('执行异常,{}'.format(_path), e) @time_me() def main(): # 创建线程池 all_task = [] pool = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix='code-read-exec') # 获取目录 get_dir(base_code_path) logging.info('共 {} 个项目'.format(len(paths))) for p in paths: all_task.append(pool.submit(rm_target, p)) # 等待所有完成 wait(all_task, return_when=ALL_COMPLETED) print("\n------所有项目拉取完毕--------") if __name__ == '__main__': # 操作目录 base_code_path = '/Users/liurenkui/workSpace/Java/my-all-code' os.chdir(base_code_path) # 最大线程数量 max_workers = 20 # 执行主方法 main()
日志示例
共 206 个项目 code-read-exec_2 [rm -rf /Users/liurenkui/workSpace/Java/my-all-code/xxx-cart/target] 完毕 code-read-exec_1 [rm -rf /Users/liurenkui/workSpace/Java/my-all-code/xxx-withdrawal/target] 完毕 code-read-exec_15 [rm -rf /Users/liurenkui/workSpace/Java/my-all-code/xxx-member/xxx-core/target] 完毕 code-read-exec_16 [rm -rf /Users/liurenkui/workSpace/Java/my-all-code/xxx-public/xxx-dtos-all/target] 完毕 ... ... ... ------所有项目拉取完毕-------- main 耗时 4 秒
未经允许请勿转载:程序喵 » Python3 多线程批量对所有 gitlab 项目删除 target 目录