此篇為學習Python多進程這個知識點是的練習Demo,有興趣的可以看一下。這 里面涉及到的知識點有:進程池(Pool)、進程間通信(Manager().Queue() > 、文件讀寫等。
Github : https://github.com/Pgrammerybj
個人博客(調試中):www.ppowan.com

# coding:utf-8
import os
from multiprocessing import Pool, Manager
# 定義一個copy文件的方法
def copy_file(file, old_folder, new_folder, queue):
# 讀取文件
fr = open(old_folder + "/" + file, "rb")
fw = open(new_folder + "/" + file, "wb")
file_size = (os.path.getsize(old_folder + "/" + file)) / 1024 // 1024
print("大?。?d" % file_size + "M|||" + (old_folder + file))
# 文件內容
while True:
content = fr.read(1024 * 1024)
fw.write(content)
if not content:
break
fr.close()
fw.close()
queue.put(file_size)
# 定義一個主方法來操作進程等
def main():
current_path = "/Users/jackyang/Movies/"
# 輸入需要拷貝的文件夾
old_folder_name = input("請輸入您要拷貝的文件夾:")
old_folder_name = current_path + old_folder_name
# 目標位置的文件夾
new_folder_name = old_folder_name + "-備份"
# 創(chuàng)建文件夾
if os.path.exists(new_folder_name):
os.removedirs(new_folder_name)
else:
os.mkdir(new_folder_name)
# 獲取copy目錄下所有的文件名
all_file = os.listdir(old_folder_name)
# 創(chuàng)建進程池
pool = Pool(5)
# 創(chuàng)建隊列管理用來進程間通信
queue = Manager().Queue()
for file in all_file:
pool.apply_async(copy_file, args=(file, old_folder_name, new_folder_name, queue))
num = 0
total = len(all_file)
# 計算出所有文件的總大小
sum_size = 0
for path in all_file:
sum_size += (os.path.getsize(old_folder_name + "/" + path)) / 1024 // 1024
print("文件總大?。?dM" % sum_size)
current_progress = 0
while num < total:
num += 1
current_progress += queue.get()
copyProgress = current_progress / sum_size
print("當前的進度是:%.f%%" % (copyProgress * 100))
if __name__ == '__main__':
main()