代码实现
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import multiprocessing
import os, time, random
def copy_file(q, file_name, old_folder_name, new_folder_name):
"""完成copy任务"""
# print("从 %s ---》 %s ,文件名为: %s" % (old_folder_name, new_folder_name, file_name))
old_f = open(old_folder_name + "/" + file_name,"rb")
file_r = old_f.read()
old_f.close()
new_f = open(new_folder_name + "/" + file_name,"wb")
new_f.write(file_r)
new_f.close()
# 若拷贝完成,则将它放入队列
q.put(file_name)
def main():
# 获取要copy的文件的名字
old_folder_name = input("请输入要copy的文件:")
# 创建一个新的文件夹
try:
new_folder_name = old_folder_name + "附件"
os.mkdir(new_folder_name)
except:
pass
# 获取文件夹中所有待copy的文件的名字 listdir
file_names = os.listdir(old_folder_name)
# for i in file_names:
# print("已经查找到 %s" % (i))
# 创建进程池
po1 = multiprocessing.Pool(5)
# 创建一个队列
q = multiprocessing.Manager().Queue()
# 向进程池中添加copy任务
for file_name in file_names:
po1.apply_async(copy_file, args=(q, file_name, old_folder_name, new_folder_name))
# copy文件
po1.close()
# po1.join()
all_file_number = len(file_names)
copy_ok = 0
while True:
file_name = q.get()
# print("已经完成拷贝 %s ." % (file_name))
copy_ok += 1
print("\r copy 的进度为 %.2f %%" % ((copy_ok/all_file_number)*100), end="")
if copy_ok >= all_file_number:
break
if __name__ == '__main__':
main()
未完待续。。。