需要源码可以直接联系拿
方案一: 直接套用脚本,需可以看懂一些脚本逻辑
在该代码中,我们使用了 multiprocessing.Process 类来创建多个进程。在主程序中,我们计算了每个进程需要拷贝的目标文件夹数量,并使用这个数量创建了一个包含多个进程的列表。然后,我们启动了所有进程,并等待它们全部执行完毕。在所有进程结束后,我们记录结束时间,并输出用时。
该程序与之前的代码是一样的,先计算每个进程需要拷贝的目标文件夹数量,然后创建多个进程,每个进程处理一部分目标文件夹的拷贝工作。最后,我们依次启动所有进程,等待它们全部执行完毕。在所有进程结束后,我们记录结束时间,并输出用时
import shutil
import os
import multiprocessing
import time
def copy_folder(source_folder, dest_folders):
"""
将文件夹 source_folder 复制到多个目标文件夹 dest_folders。
如果目标文件夹已经存在,则先清空目标文件夹,然后复制。
"""
for dest_folder in dest_folders:
try:
if os.path.exists(dest_folder):
shutil.rmtree(dest_folder)
shutil.copytree(source_folder, dest_folder)
print(f"成功将 {source_folder} 复制到 {dest_folder}")
except Exception as e:
print(f"复制 {source_folder} 到 {dest_folder} 时发生错误:e}")
if __name__ == "__main__":
# 需要复制的原始文件夹
source_folder = "source/folder"
# 需要复制到的多个目标文件夹
dest_folders = ["/path/folder_1", "/path/folder_2", "/path/folder_3"]
# 计算每个进程需要拷贝的目标文件夹数量
processes_num = len(dest_folders)
folders_per_process = len(dest_folders) // processes_num
# 创建进程列表
processes = []
for i in range(processes_num):
start = i * folders_per_process
end = start + folders_per_process
if i == processes_num - 1:
end = len(dest_folders)
process = multiprocessing.Process(target=copy_folder, args=(source_folder, dest_folders[start:end]))
processes.append(process)
# 记录开始时间
start_time = time.time()
# 启动所有进程
for process in processes:
process.start()
# 等待所有进程结束
for process in processes:
process.join()
# 记录结束时间并输出用时
end_time = time.time()
print(f"复制用时: {end_time - start_time} 秒")
方案二:直接调用封装脚本(写用例,执行脚本即可)
脚本实现封装后,只需要在MultiProcessCopy.yaml文件中写用例即可,此后执行Multiprocess_Copy.py脚本即实现多线程拷贝文件夹下所有内容到指定目录
目录介绍:
MultiProcessCopy.yaml配置拷贝文件的源地址和目标地址
source_folder: 原始文件夹路径
dest_folders: 需存放目标文件夹,可多个同时填写
MultiProcess:
source_folder: \\127.0.0.1\d$\exportdir
dest_folders:
- \\127.0.0.2\d$\path1
- \\127.0.0.2\d$\path2
-
PublicConfig.py脚本: 配置读取信息,方便调用
import os
from Public_Utils.util_yaml import YamlReader
class YamlPath:
def __init__(self):
current = os.path.abspath(__file__)
self.base_dir = os.path.dirname(os.path.dirname(current))
def get_multiprocess_file(self):
_config_path = self.base_dir + os.sep + "Public_Config\Public_yaml"
self._config_file = _config_path + os.sep + "MultiProcessCopy.yaml"
return self._config_file
class ConfigYaml:
def __init__(self): #初始yaml读取配置文件
self.multiprocess_config= YamlReader(YamlPath().get_multiprocess_file()).yaml_data()
def get_multiprocess_yaml(self):
return self.multiprocess_config['MultiProcess']
if __name__ == '__main__':
pass
Multiprocess_Copy.py执行脚本
import multiprocessing
import os
import shutil
import time
from Public_Config.PublicConfig import ConfigYaml
class MultiProcess:
def copy_folder(self,source_folder,dest_folders):
"""
将原文件夹复制到多个目标文件夹下
:return:
"""
for dest_folder in dest_folders:
try:
if os.path.exists(dest_folder):
shutil.rmtree(dest_folder)
shutil.copytree(source_folder,dest_folder)
print(f"has copied {source_folder} to {dest_folder}")
except Exception as e:
print(f"failed copy {e}")
def Multi_copy_folder(self): #多进程程同时拷贝源文件夹到其他多个目录
source_folder = ConfigYaml().get_multiprocess_yaml()['source_folder'] # 需要复制的原始文件夹
dest_folders = ConfigYaml().get_multiprocess_yaml()['dest_folders'] # 需要复制到的目标文件夹
#计算每个进程需要拷贝第目标文件夹数量
process_num = len(dest_folders)
folders_per_process = len(dest_folders) // process_num
#创建进程列表
processes = []
for i in range(process_num):
start = i * folders_per_process
end = start + folders_per_process
if i == process_num - 1:
end = len(dest_folders)
process = multiprocessing.Process(target=self.copy_folder, args=(source_folder, dest_folders[start:end]))
processes.append(process)
#记录开始时间
start_time = time.time()
# 启动所有进程
for thread in processes:
thread.start()
# 等待所有进程结束
for thread in processes:
thread.join()
# 结束时间
end_time = time.time()
print(f"复制用时{end_time - start_time}")
if __name__ == '__main__':
pass
MultiProcess().Multi_copy_folder()
util_yaml.py
import os
import yaml
class YamlReader:
#初始化,判断文件是否存在
def __init__(self,yaml_file):
if os.path.exists(yaml_file):
self.yaml_file = yaml_file
else:
raise FileNotFoundError("yaml文件不存在")
self._data = None
self._data_all = None
def yaml_data(self): #yaml文件读取 --单个文档读取
#第一次调用data,读取yaml文档,如果不是,直接返回之前保存的数据
if not self._data:
with open(self.yaml_file,'rb') as f:
self._data = yaml.safe_load(f)
return self._data
def yaml_data_all(self): #多个文档的读取
if not self._data_all:
with open(self.yaml_file,'rb') as f:
self._data_all = yaml.safe_load_all(f)
return self._data_all