Python day16_进程

进程池完成文件夹拷贝器

import os
import shutil # 文件操作的高级模块
import multiprocessing
import time


# 拷贝文件的任务
def copy_file_work(src_dir, dst_dir, file_name):
        # 查看当前进程号
    print(multiprocessing.current_process().pid)
    # 源文件的路径
    src_file_path = src_dir + "/" + file_name
    # 目标文件的路径
    dst_file_path = dst_dir + "/" + file_name
    with open(dst_file_path, "wb") as dst_file:
        with open(src_file_path, "rb") as src_file:
            while True:
                src_file_data = src_file.read(1024)
                if src_file_data:
                    # 读取到原文件的数据写入到目标文件里面
                    dst_file.write(src_file_data)
                else:
                    break
    time.sleep(0.1)


if __name__ == '__main__':
    # 源目录
    src_dir = "test"
    # 目标目录
    dst_dir = "/home/python/Desktop/test"

    if os.path.exists(dst_dir):
        # 删除指定目录的文件夹,把文件夹里面的所有内容全部删除
        shutil.rmtree(dst_dir)
    # 创建指定目录的文件夹
    os.mkdir(dst_dir)
    # 获取原目录的文件名列表
    file_name_list = os.listdir(src_dir)

    # 创建进程池
    pool = multiprocessing.Pool(3)

    # 遍历文件名列表获取对应的文件名
    for file_name in file_name_list:
        # 使用进程池完成文件的异步拷贝
        pool.apply_async(copy_file_work, (src_dir, dst_dir, file_name))
    # 关闭进程池
    pool.close()
    # 主进程等待进程池执行完成以后程序再退出
    pool.join()

你可能感兴趣的:(Python day16_进程)