Pythonはマルチプロセスコピーファイルを実現

2273 ワード

from multiprocessing import Pool,Manager
import os


def copyFileTask(names,oldFolderName,newFolderName,queue):    #       
    fr = open(oldFolderName+"/"+names)
    fw = open(newFolderName+"/" + names , "w")
    content = fr.read()
    fw.write(content)
    fw.close()
    fr.close()
    queue.put(names)                #      ,      

def main():
    oldFolderName = input("please input the name that you want to delete: ")      #           
    newFolderName = oldFolderName + "-  "
    os.mkdir(newFolderName)     #       
    fileName = os.listdir(oldFolderName)   
    pool = Pool(5)              #      
    queue = Manager().Queue()
    for i in fileName:
        pool.apply_async(copyFileTask,args=(i,oldFolderName,newFolderName,queue))

    num = 0
    allNum = len(fileName)
    while(True):
        queue.get()
        num += 1
        copyRate = num / allNum
        print("\rcopy    :%.2f%%"%(copyRate*100),end="")
        if num == allNum:
            break
if __name__ == "__main__":
    main()