python多进程(加入进程池)操作常见案例

  

本文实例讲述了python多进程(加入进程池)操作。分享给大家供大家参考,具体如下:

  

<强>一、多进程复制多个文件

        进口多处理   进口操作系统   导入的时间   #复制文件,传入文件名   def copy_file (old_file_name old_name):   new_file_name=' new_file '   new_name=old_name   如果不是os.path.exists (new_file_name):   os.makedirs (new_file_name)   打开(old_file_name +‘/? old_name, rb) f:   file_content=f.read ()   打开(new_file_name +‘/? new_name, wb) f:   f.write (file_content)   if __name__==癬_main__”:   old_file_name=' old_file '   name_list=os.listdir (old_file_name)   time_old=time.time ()   在name_list名字:=多处理过程。过程(目标=copy_file args=(old_file_name、名称))   process.start ()   time_new=time.time ()   打印(“执行时间:% f ' % (time_new - time_old))      之前      

<强>二、优化加入进程池,并显示复制进度:

        进口多处理   进口操作系统   导入的时间   #复制文件,传入文件名   def copy_file (old_file_name old_name,队列):   new_file_name=' new_file '   new_name=old_name   如果不是os.path.exists (new_file_name):   os.makedirs (new_file_name)   打开(old_file_name +‘/? old_name, rb) f:   file_content=f.read ()   打开(new_file_name +‘/? new_name, wb) f:   f.write (file_content)   queue.put (new_file_name)   if __name__==癬_main__”:   old_file_name=' old_file ' #存放文件的文件名   name_list=os.listdir (old_file_name) #取出所有文件的文件名   队列=multiprocessing.Manager () .Queue() #创建队列对象,用于计算复制完成百分比   阿宝=multiprocessing.Pool(3) #创建线程池   time_old=time.time() #用于计算花费时间   在name_list名字:   阿宝。apply_async (copy_file (old_file_name、名称、队列))   po.close ()   指数=0   而真正的:   指数+=1   queue.get ()   打印(‘\ r以保存%。2 f % % %((索引/len (name_list)) * 100),结束=")   如果指数==len (name_list):   打破   time_new=time.time ()   打印(“执行时间:% f ' % (time_new - time_old))      之前      

<强>三,多进程聊天器:

        进口多处理   进口套接字   进口线程   #需求:   # 1。主进程创建一个TCPconnect   # 2。主进程连接后创建进程开启一个新的Socketconnect   # 3。进程里创建线程不断的接收和提示发送消息   #有连接时新创建一个进程处理聊天   def speak_send (tcp_msg):   而真正的:   测试=输入(“请输入要发送的消息”)   tcp_msg.send (test.encode (utf - 8))   def speak_rec (tcp_msg):   而真正的:   print (tcp_msg.recv (1024) .decode (gbk))   #开启的进程聊天   def speak_process (tcp_sock、tcp_msg、ip):   打印(“开启进程”)   # 5。开线程循环接收消息   msg_rec=线程。线程(目标=speak_rec args=(tcp_msg,))   #打印(tcp_msg.recv (1024) .decode (gbk))   # 6。开线程循环发送消息   msg_send=线程。线程(目标=speak_send args=(tcp_msg,))   msg_rec.start ()   msg_send.start ()   msg_rec.join ()   msg_send.join ()   # 7。关闭   # tcp_msg.close ()   def main ():   # 1创建TCP对象   tcp_sock=socket.socket(插座。AF_INET socket.SOCK_STREAM)   # 2。绑定ip和端口   tcp_sock。绑定(",9999)   # 3。改主动为被动   tcp_sock.listen (128)   # 4.接受接收味精和ip   而真正的:   tcp_msg、ip=tcp_sock.accept ()=多处理过程。过程(目标=speak_process args=(tcp_sock、tcp_msg、ip))   process.start ()   if __name__==癬_main__”:   main ()      之前      

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》,《Python数据结构与算法教程》、《Python函数使用技巧总结》,《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python + MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总》

  

希望本文所述对大家Python程序设计有所帮助。

python多进程(加入进程池)操作常见案例