代码
import multiprocessing
import os
def copy_file(file_name, source_folder, target_folder, queue):
"""
完成拷贝任务
:param file_name: 需要拷贝的文件名
:param source_folder: 源文件夹
:param target_folder: 目标文件夹
:param queue: 队列, 拷贝完成时往队列中存放文件名
:return: None
"""
try:
source_file = open(source_folder + "/" + file_name, "rb")
target_file = open(target_folder + "/" + file_name, "wb")
while True:
source_data = source_file.read(1024)
if len(source_data) == 0:
break
target_file.write(source_data)
source_file.close()
target_file.close()
except Exception as error:
print(error)
queue.put(file_name)
def main():
source_folder = input("请输入要拷贝文件夹的名字:")
source_file_list = os.listdir(source_folder)
target_folder = source_folder + "[复件]"
if not os.path.isdir(target_folder):
os.mkdir(target_folder)
process_pool = multiprocessing.Pool(2)
queue = multiprocessing.Manager().Queue()
for file_name in source_file_list:
process_pool.apply_async(copy_file, (file_name, source_folder, target_folder, queue))
process_pool.close()
done_file_list = list()
while True:
done_filename = queue.get()
done_file_list.append(done_filename)
speed_of_progress = len(done_file_list) / len(source_file_list)
print("\r当前的拷贝的总进度为{}% ".format(speed_of_progress * 100), end="")
if speed_of_progress >= 1:
break
print()
process_pool.join()
if __name__ == '__main__':
main()
运行效果
拷贝结果