使用进程池进行大批量文件拷贝实现(Python)
2018-03-20 10:48
676 查看
from multiprocessing import Process from multiprocessing import Pool from multiprocessing import Manager import hashlib, os class fileCopy: def __init__(self, source, target): self.source = source self.target = target def __enter__(self): self.sf = open(self.source, 'r+b') self.tf = open(self.target, 'w+b') return self def __exit__(self, exc_type, exc_val, exc_tb): self.sf.close() self.tf.close() def startCopy(self): while True: b = self.sf.read(2048) if not b: break self.tf.write(b) self.tf.flush() def compute_digest(filename): BUFSIZE = 2048 try: f = open(filename, 'r+b') except IOError: return None # 确定算法类型 digest = hashlib.sha512() while True: chunk = f.read(BUFSIZE) if not chunk: break digest.update(chunk) f.close() return digest.hexdigest() def copyFinish(*args): global sourDic, targDic source_map = compute_digest(sourDic + args[0][0]) target_map = compute_digest(targDic + args[0][0]) if source_map != target_map: print("拷贝失败:", args[0][0]) else: args[0][1].put(args[0][0]) def fileTarget(*args): global sourDic, targDic with fileCopy(sourDic + args[0], targDic + args[0]) as f: f.startCopy() return (args[0], args[1]) def main(): dic = os.listdir(sourDic) dicL = [x for x in dic if not os.path.isdir(sourDic + x)] if len(dicL) > 0: print("拷贝中. . .") q = Manager().Queue() p = Pool() for fileName in dicL: p.apply_async(fileTarget, (fileName, q), callback=copyFinish) p.close() # p.join() allCount = len(dicL) count = 0 while True: item = q.get() if item: count += 1 length = str(round((count / allCount)*100, 1)) + "%" print("\r拷贝文件: %d, 拷贝进度: %s" % (count, length), end='') if count == allCount: print() break print("文件拷贝完成: ") else: print("文件夹为空") sourDic = "./files/" targDic = "./cp_process/" if __name__ == '__main__': main()
相关文章推荐
- python使用paramiko实现远程拷贝文件的方法
- Python基础——文件拷贝(从手动实现到shutil的使用)
- Python下使用optparse模块实现对多个文件进行统计【二】
- python文件操作_对文件进行复制拷贝_代码实现
- Python笔记–IAR使用Python脚本实现自动对烧录文件进行处理
- python使用paramiko实现远程拷贝文件的方法
- Python使用Paramiko模块实现远程文件拷贝
- 写个python 脚本实现文件的递归拷贝
- 使用pscp实现Windows 和 linux服务器间远程拷贝文件
- python 实现文件的递归拷贝实现代码
- Python下使用tarfile模块来实现文件归档压缩与解压
- Java拷贝文件的例子(使用channel实现)
- 使用python来访问Hadoop HDFS存储实现文件的操作
- 【python】利用sftp及rsa密匙实现远程拷贝文件
- 通过python的import hooks实现像引用代码一样使用配置文件
- Java拷贝文件的例子(使用channel实现)
- python 实现文件的递归拷贝
- 使用Python进行二进制文件读写
- 使用Python进行二进制文件读写(转)
- Python实现在不同Linux主机之间拷贝文件