pyhon - 监听u盘插入并复制

import time
from shutil import copytree
from psutil import disk_partitions

copyFlag = False


def usbCopy(driver):
    try:
        path = r"D:\usb-" + time.strftime("%Y%m%d%H%M%S", time.localtime())
        print(f"开始复制,复制路径: {path}")
        copytree(driver, path)
        print("复制结束")
        return True
    except Exception as e:
        print(e)
        return False


while True:
    #  设置休眠时间
    time.sleep(5)
    #  检测所有的驱动器
    for item in disk_partitions():
        print(f"{item.device} {item.opts}")
        if "removable" in item.opts:
            print("发现usb驱动:", item.device)
            copyFlag = usbCopy(item.device)
    if copyFlag == True:
        break

posted @ 2023-08-03 16:38  wstong  阅读(56)  评论(0编辑  收藏  举报