python

超轻量级php框架startmvc

python多线程案例之多任务copy文件完整实例

更新时间:2020-08-05 02:24:01 作者:startmvc
本文实例讲述了python多线程案例之多任务copy文件。分享给大家供大家参考,具体如下:impor

本文实例讲述了python多线程案例之多任务copy文件。分享给大家供大家参考,具体如下:


import os
import multiprocessing
def copy_file(q,file_name, old_folder_name, new_folder_name):
 """完成文件的复制"""
 old_f = open(old_folder_name+"/"+file_name, "rb")
 content = old_f.read()
 old_f.close()
 new_f = open(new_folder_name+"/"+file_name, "wb")
 new_f.write(content)
 new_f.close()
 # print("从%s--->到%s 复制文件%s成功!" % (old_folder_name, new_folder_name, file_name))
 q.put(file_name)
def main():
 # 1.获取用户要copy的文件夹名称
 old_folder_name = input("请输入要copy的文件夹:")
 # 2.创建一个新的文件夹
 try:
 new_folder_name = old_folder_name + "复件"
 os.mkdir(new_folder_name)
 except:
 pass
 # 3.获取所有待copy的文件名称 listdir()
 file_names = os.listdir(old_folder_name)
 print(file_names)
 # 4.创建进程池
 po = multiprocessing.Pool(2)
 # 5.创建一个队列
 q = multiprocessing.Manager().Queue()
 # 6.向进程池中添加copy文件的任务
 for file_name in file_names:
 po.apply_async(copy_file, args=(q,file_name, old_folder_name, new_folder_name))
 po.close()
 # po.join()
 all_file_num = len(file_names) # 统计所有的文件个数
 copy_ok_num = 0
 while True:
 file_name = q.get()
 # print("已经完成copy :%s" % file_name)
 copy_ok_num += 1
 print("\r复制的进度为:%.2f %%" % (copy_ok_num*100/all_file_num),end='')
 if copy_ok_num >= all_file_num:
 break
if __name__ == '__main__':
 main()

python 多线程 多任务 copy文件