1. 程式人生 > >使用python完成多工複製

使用python完成多工複製

 
 

多工可以說是多執行緒,多程序,即在同一時間可以完成多個任務。不管是在python開發過程中還是在其它開發過程中,多執行緒和多程序開發都是不可缺少的,這不僅僅可以大大提高軟體的執行效率,更能方便工具資源的管理。就併發和並行來說,併發不屬於多線/程序,並行屬於多線/程序。本文,通過使用執行緒池和訊息佇列實現了多工複製的功能以及複製完成百分比的輸入。一起來看看如何實現的吧。
首先:
為了建立執行緒池和訊息佇列引入multiprocessing模組
為了遍歷全部檔案匯入os模快

import multiprocessing

import os

然後:
對將要實現的功能進行分析

獲取要拷貝的資料夾名字
建立一個新的資料夾
獲取資料夾中所有待複製的檔案
建立程序池
建立佇列
複製原資料夾中的檔案複製到新資料夾中去



最後: 根據我們前期的分析,逐步實現我們的程式碼,詳細程式碼如下所示
import os import multiprocessing def copy_file(queue, filename, old_folder_name, new_folder_name): # 以二進位制形式開啟檔案 data = open(old_folder_name + "/" + filename, "rb") # 讀取檔案 temp = data.read() data.close() # 新建檔案,寫入原始檔內容 new_data = open(new_folder_name + "/" + filename, "
wb") new_data.write(temp) new_data.close() # 如果拷貝完一個檔案就向佇列裡寫一個訊息,表示已經完成 queue.put(filename) def main(): # 1.獲取要拷貝的資料夾的名字 old_folder_name = input("請輸入要拷貝的資料夾的名字:") # 2.建立一個新的資料夾(檔案存在就pass,不存在就建立) try: new_folder_name = "D:\demo" os.mkdir(new_folder_name) except: pass # 3.獲取資料夾中所有的待copy的檔案 os.listdir()
file_names = os.listdir(old_folder_name) print(file_names) # 4.建立程序池,多工執行復制操作 po = multiprocessing.Pool(3) # 5.建立佇列 queue = multiprocessing.Manager().Queue() # 6.複製原資料夾中的檔案到新的資料夾中 for i in file_names: # print("要拷貝的檔案:%s" % i) po.apply_async(copy_file, args=(queue, i, old_folder_name, new_folder_name)) po.close() # 獲取所有檔案的個數 all_files = len(file_names) # 當前已完成檔案個數 current_file = 0 while True: data = queue.get() # print("已經完成:%s 檔案的拷貝" % data) # 由於後面已經實現了複製完成的百分比,這裡註釋了 current_file += 1 print("\r拷貝的進度為:%.2f %%" % ((current_file / all_files) * 100), end="") if current_file >= all_files: break print() if __name__ == '__main__': main()