From multiprocessing import pool,manager import os,timedef copyfiletask (fileName , Oldfoldername,newfoldername,queue): Fr = open (oldfoldername+ "/" +filename, ' R ', encoding= ' UTF-8 ') FW = open (newfoldername+ "/" +filename, ' W ', encoding= ' UTF-8 ') #复制while True:content = Fr.read (1024x768) If len (content) == 0:breakfw.write (content) #关闭文件fr. Close () Fw.close () Queue.put ( FileName) Def main ():oldfoldername = ' Test ' #input ("Please enter the folder name to be copied:") #创建目录newFolderName = oldfoldername+ "[Copy]" Os.mkdir (newfoldername) #获取文件列表fileList = os.listdir (oldfoldername) # Copy Pool = pool (5) #消息队列queue = manager () using a multi-process approach. Queue () For file in filelist: #copyFileTask (file,oldfoldername,newfoldername,queue) pool.apply_ Async (copyfiletask,args= (file,oldfoldername,newfoldername,queue)) Num = 0total = len ( fileList) While num<total:queue.get () Num += 1rate = num/totaL*100print (' \ R ' The Progress of replication is:%.2f%% '%rate,end= ") #关闭进程池, no longer accepting new processes #pool.close () #主进程阻塞等待子进程的退出 #pool.join () if __name_ _ == ' __main__ ': T_start = time.time () Main () T_stop = time.time () print ("\ n executed, time consuming %0.2f "% (T_stop-t_start))
Single process:
C:\users\administrator>python d:\python\copy.py
The progress of replication is: 100%
Execution completed, time consuming 6.53
Multi-process:
C:\users\administrator>python d:\python\copy.py
The progress of replication is: 100%
Execution completed, time consuming 6.59
Multi-process Copy file