进程池复制文件和回调函数

“”"
使用进程池方式实现多任务
复制一个文件夹下的所有文件(一个文件的复制由一个进程来完成)
文件夹目录:D:/file
注意:需要使用管道队列Manager().Queue()

目的:进程池异步任务中 回调函数的使用
“”"
from multiprocessing import Manager,Pool
import time,random,os
#复制文件
def copyFile(srcFile,toFile,queue):
try:
fr =open(srcFile,‘r’,encoding=‘utf-8’)
fw =open(toFile,‘w’,encoding=‘utf-8’)
content = fr.read()
fw.write(content)
#将已经复制完毕的文件 的信息存入队列中
# queue.put(toFile)
time.sleep(random.random()*3)
finally:
fr.close()
fw.close()

#回调函数 (与某个进程处理的任务相关联,当该进程处理完该任务以后,回调函数被调用)
def finished(queue,file,total):
queue.put(file)
print((queue.qsize(),total))
print(‘文件{0}复制完成’.format(file))

if name == ‘main’:
#创建管道队列
queue = Manager().Queue()
#创建进程池对象
pool = Pool()
#准备好源文件夹
srcDir = ‘D:/file’

 #创建好目标文件夹
 toDir = srcDir+'-复件'
 os.makedirs(toDir)

 list_files  = os.listdir(srcDir)
 total = len(list_files)
 for file in  list_files:
     #源文件
     srcFile =srcDir +'/'+file
     #目标文件
     toFile =toDir +'/'+file
     # 同步执行多任务
     # pool.apply(copyFile,args=(srcFile,toFile,queue))
     # 异步执行多任务
     pool.apply_async(copyFile,args=(srcFile,toFile,queue),callback=finished(queue,file,total))
 #先关闭进程池对象,防止进程池里边的进程被修改
 pool.close()
 #阻塞主进程
 pool.join()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值