Python多進程練習(通過多進程、進程間通信等實現(xiàn)60個G的電影拷貝)

此篇為學習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()

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,836評論 6 427
  • afinalAfinal是一個android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,876評論 2 45
  • 不想接受父母指定的人生,自己又不知道該往哪兒走。面對別人的意見,總有無數(shù)個理由去反駁,覺得別人不懂自己,就這樣一天...
    大健濤閱讀 154評論 0 1
  • 1,感恩坦坦學員們的互相影響,成就了我能每天早上堅持讀(大學)。 2,感恩自己現(xiàn)在一點點的進步,不會受兒子情緒的影...
    麗人d閱讀 160評論 0 0
  • 心中有信念, ...
    張維群閱讀 301評論 0 0

友情鏈接更多精彩內容