脚本运行后,OS总是在一个进程里。别的进程一直不动。麻烦大家帮忙找找原因。
[Python] 纯文本查看 复制代码 import os
import hashlib
import asyncio
import concurrent.futures
import multiprocessing
def calc_md5(file_path):
# 计算文件的MD5值
md5 = hashlib.md5()
with open(file_path, "rb") as f:
while True:
data = f.read(1024000)
if not data:
break
md5.update(data)
return md5.hexdigest()
async def calc_md5_async(file_path, executor):
# 异步地调用calc_md5函数
loop = asyncio.get_event_loop()
md5 = await loop.run_in_executor(executor, calc_md5, file_path)
return md5
async def main(file_paths, executor):
# 主函数
tasks = [calc_md5_async(file_path, executor) for file_path in file_paths] # 任务列表
results = await asyncio.gather(*tasks) # 等待所有任务完成
for file_path, md5 in zip(file_paths, results):
print(f"{file_path}: {md5}") # 打印结果
def process_start(file_paths):
# 进程启动函数
executor = concurrent.futures.ThreadPoolExecutor(max_workers=4) # 线程池
asyncio.run(main(file_paths, executor)) # 运行主函数
def task_start(dir_path, flag=10000):
# 任务启动函数
file_paths = [] # 文件路径列表
for root, dirs, files in os.walk(dir_path): # 遍历目录
for file in files:
file_paths.append(os.path.join(root, file)) # 添加文件路径
pool = multiprocessing.Pool(processes=4) # 进程池
for i in range(0, len(file_paths), flag): # 每flag个文件启动一个进程
pool.apply_async(process_start, (file_paths[i:i+flag],)) # 异步地执行进程
pool.close() # 关闭进程池
pool.join() # 等待所有进程结束
if __name__ == "__main__":
task_start("D:\\sd-webui-aki-v4.1\\models\\Stable-diffusion") # 读取指定目录
|