欢迎访问宙启技术站
智能推送

Python中的ThreadingMixIn:实现多线程文件复制

发布时间:2023-12-23 06:12:04

ThreadingMixIn是Python中提供的一个混合类,用于将多线程功能添加到自定义类中。通过继承ThreadingMixIn类,我们可以实现多线程文件复制。

下面是一个使用ThreadingMixIn实现多线程文件复制的示例代码:

import threading
import shutil

class FileCopyThread(threading.Thread):
    def __init__(self, src_file, dst_file):
        threading.Thread.__init__(self)
        self.src_file = src_file
        self.dst_file = dst_file

    def run(self):
        # 执行文件复制操作
        shutil.copy2(self.src_file, self.dst_file)
        print(f"Copy {self.src_file} to {self.dst_file} completed.")


class FileCopyWithThreads:
    def __init__(self, src_files, dst_folder):
        self.src_files = src_files
        self.dst_folder = dst_folder

    def copy_files(self):
        for src_file in self.src_files:
            # 构建目标文件路径
            dst_file = f"{self.dst_folder}/{src_file}"
            # 创建并启动线程
            thread = FileCopyThread(src_file, dst_file)
            thread.start()


if __name__ == "__main__":
    # 源文件列表
    src_files = ["file1.txt", "file2.txt", "file3.txt"]
    # 目标文件夹
    dst_folder = "destination"

    # 创建并启动多线程文件复制对象
    file_copy_obj = FileCopyWithThreads(src_files, dst_folder)
    file_copy_obj.copy_files()

上述代码中,FileCopyThread类继承自threading.Thread,重写了run()方法,其中调用了shutil.copy2()函数实现文件复制操作。在创建并启动线程时,传入源文件路径和目标文件路径作为参数。

FileCopyWithThreads类中的copy_files()方法循环遍历源文件列表,为每个源文件创建并启动一个线程。通过调用start()方法启动线程后,会自动调用run()方法中的代码。

在主程序中,首先定义源文件列表和目标文件夹路径。然后,创建并启动多线程文件复制对象FileCopyWithThreads,并调用copy_files()方法开始复制文件。

通过使用ThreadingMixIn,我们可以在Python中很方便地实现多线程文件复制。在这个例子中,每个源文件都会启动一个新线程,实现并发的文件复制操作,提高了文件复制的效率。