Initial commit: U盘备份工具 (Udisk Backup Tool for Windows)
Windows GUI tool to backup USB drives with full mirror sync, hash-based incremental skip, robust copy and failure logging.
This commit is contained in:
commit
3909f100d0
5 files changed
+706
No files matched your search
+14
@@ -0,0 +1,14 @@
|
||||
# 编译产物(通过 GitHub Releases 分发)
|
||||
*.exe
|
||||
*.zip
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
build/
|
||||
dist/
|
||||
*.spec
|
||||
|
||||
# 系统文件
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 SamBuuuu
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,52 @@
|
||||
# U盘备份工具 (Udisk Backup)
|
||||
|
||||
一款 Windows 平台的开源 U 盘备份工具,带图形界面(GUI),支持全量镜像备份与增量复制。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- 🖥️ **图形界面** — 基于 tkinter,无需命令行操作
|
||||
- 💾 **自动检测 U 盘** — 枚举可移动磁盘,可选包含固定磁盘(读卡器/USB 硬盘)
|
||||
- 🔄 **全量镜像备份** — 目标目录与 U 盘完全一致,自动清理源中已删除的文件
|
||||
- ⚡ **增量跳过** — 通过 SHA-256 哈希对比,未变化的文件秒跳过
|
||||
- 🛡️ **健壮复制** — 自动清除只读属性、重试复制、1MB 缓冲大文件复制
|
||||
- 📋 **失败记录** — 复制失败的文件完整记录,不静默跳过
|
||||
- ⏹️ **可取消** — 备份过程中随时中止
|
||||
- 🚫 **系统目录豁免** — 自动跳过 `System Volume Information`、`$RECYCLE.BIN` 等系统目录
|
||||
- 📁 **长路径支持** — 处理 Windows 长路径限制
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 直接运行(需要 Python 3.8+)
|
||||
|
||||
```bash
|
||||
python usb_backup.py
|
||||
```
|
||||
|
||||
无需第三方依赖(仅标准库:tkinter / ctypes / hashlib)。
|
||||
|
||||
### 打包为 exe(可选)
|
||||
|
||||
```bash
|
||||
pip install pyinstaller
|
||||
pyinstaller --onefile --windowed --icon icon.ico usb_backup.py
|
||||
```
|
||||
|
||||
打包产物在 `dist/U盘备份工具.exe`,可分发到无 Python 环境的 Windows 机器。
|
||||
|
||||
> 预编译的 exe 请从 [Releases](../../releases) 下载。
|
||||
|
||||
## 备份位置
|
||||
|
||||
默认备份到 `E:\U盘备份`,按 U 盘卷标自动建子目录。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
├── usb_backup.py # 主程序(单文件,~600 行)
|
||||
├── icon.ico # 程序图标
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 许可证
|
||||
|
||||
[MIT](LICENSE)
|
||||
+619
@@ -0,0 +1,619 @@
|
||||
import os
|
||||
import sys
|
||||
import stat
|
||||
import shutil
|
||||
import hashlib
|
||||
import threading
|
||||
import ctypes
|
||||
|
||||
# ==================== GUI ====================
|
||||
import tkinter as tk
|
||||
from tkinter import ttk, messagebox, filedialog
|
||||
|
||||
# ==================== 常量 ====================
|
||||
BACKUP_ROOT = r"E:\U盘备份"
|
||||
BUF_SIZE = 1024 * 1024 # 1MB 复制缓冲区
|
||||
|
||||
# 系统目录:无法读取也没意义,直接跳过(全量镜像时也不删除它们)
|
||||
SYSTEM_DIRS = {
|
||||
"System Volume Information",
|
||||
"$RECYCLE.BIN",
|
||||
"RECYCLER",
|
||||
"$Recycle.Bin",
|
||||
".Trash-1000",
|
||||
"System Volume Information",
|
||||
"SystemVolumeInformation",
|
||||
}
|
||||
|
||||
|
||||
# ==================== USB 检测 ====================
|
||||
def get_usb_drives(include_fixed=False):
|
||||
"""返回可移动磁盘(U盘)的盘符列表;include_fixed 时也包含固定磁盘(读卡器/USB硬盘)"""
|
||||
drives = []
|
||||
bitmask = ctypes.windll.kernel32.GetLogicalDrives()
|
||||
for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
|
||||
if bitmask & 1:
|
||||
drive = f"{letter}:\\"
|
||||
dtype = ctypes.windll.kernel32.GetDriveTypeW(drive)
|
||||
if dtype == 2: # DRIVE_REMOVABLE
|
||||
drives.append(drive)
|
||||
elif include_fixed and dtype == 3: # DRIVE_FIXED
|
||||
drives.append(drive)
|
||||
bitmask >>= 1
|
||||
return drives
|
||||
|
||||
|
||||
def get_volume_name(drive):
|
||||
"""获取磁盘卷标"""
|
||||
buf = ctypes.create_unicode_buffer(260)
|
||||
ctypes.windll.kernel32.GetVolumeInformationW(
|
||||
drive, buf, 260, None, None, None, None, 0
|
||||
)
|
||||
return buf.value if buf.value else "(无卷标)"
|
||||
|
||||
|
||||
def get_drive_info(drive):
|
||||
"""获取磁盘信息 (总大小, 可用空间)"""
|
||||
free = ctypes.c_longlong(0)
|
||||
total = ctypes.c_longlong(0)
|
||||
ctypes.windll.kernel32.GetDiskFreeSpaceExW(
|
||||
drive, None, ctypes.byref(total), ctypes.byref(free)
|
||||
)
|
||||
return total.value, free.value
|
||||
|
||||
|
||||
def format_size(size_bytes):
|
||||
"""格式化字节大小为可读字符串"""
|
||||
for unit in ("B", "KB", "MB", "GB", "TB"):
|
||||
if size_bytes < 1024:
|
||||
return f"{size_bytes:.1f} {unit}"
|
||||
size_bytes /= 1024
|
||||
return f"{size_bytes:.1f} PB"
|
||||
|
||||
|
||||
# ==================== 长路径 & 文件系统工具 ====================
|
||||
def _lp(path):
|
||||
"""将路径转为 Windows 长路径格式 (prefix + path),支持超过 260 字符的路径"""
|
||||
if os.name == "nt" and not path.startswith("\\\\?\\"):
|
||||
return "\\\\?\\" + os.path.abspath(path)
|
||||
return path
|
||||
|
||||
|
||||
def compute_file_hash(filepath):
|
||||
"""计算文件 MD5 (用于快速比较)"""
|
||||
hasher = hashlib.md5()
|
||||
try:
|
||||
with open(_lp(filepath), "rb") as f:
|
||||
while True:
|
||||
chunk = f.read(BUF_SIZE)
|
||||
if not chunk:
|
||||
break
|
||||
hasher.update(chunk)
|
||||
return hasher.hexdigest()
|
||||
except (OSError, PermissionError):
|
||||
return None
|
||||
|
||||
|
||||
def files_differ(src, dst):
|
||||
"""
|
||||
判断源文件和目标文件是否不同。
|
||||
先比大小 + 修改时间(FAT 时间精度为 2 秒,允许误差),
|
||||
大小相同但时间不同的,用哈希最终确认,避免误判。
|
||||
"""
|
||||
try:
|
||||
src_stat = os.stat(_lp(src))
|
||||
dst_stat = os.stat(_lp(dst))
|
||||
except OSError:
|
||||
return True
|
||||
|
||||
if src_stat.st_size != dst_stat.st_size:
|
||||
return True
|
||||
if abs(src_stat.st_mtime - dst_stat.st_mtime) <= 2.0:
|
||||
return False
|
||||
# 大小一致但 mtime 有出入:用内容哈希确认
|
||||
src_hash = compute_file_hash(src)
|
||||
dst_hash = compute_file_hash(dst)
|
||||
if src_hash is None or dst_hash is None:
|
||||
return True
|
||||
return src_hash != dst_hash
|
||||
|
||||
|
||||
def clear_readonly(path):
|
||||
"""清除文件的只读属性(Windows 上只读文件无法被覆盖/删除)"""
|
||||
try:
|
||||
os.chmod(_lp(path), stat.S_IWRITE | stat.S_IREAD)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def safe_remove(path):
|
||||
"""安全删除文件/目录,先清除只读属性"""
|
||||
try:
|
||||
if os.path.isdir(_lp(path)):
|
||||
_clear_tree_readonly(path)
|
||||
shutil.rmtree(_lp(path), ignore_errors=True)
|
||||
else:
|
||||
clear_readonly(path)
|
||||
try:
|
||||
os.remove(_lp(path))
|
||||
except OSError:
|
||||
pass
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _clear_tree_readonly(root):
|
||||
"""递归清除目录树内所有文件的只读属性,避免删不掉"""
|
||||
try:
|
||||
for dirpath, _, filenames in os.walk(_lp(root)):
|
||||
for fn in filenames:
|
||||
clear_readonly(os.path.join(dirpath, fn))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_dir(path):
|
||||
"""确保目录存在(支持长路径)"""
|
||||
os.makedirs(_lp(path), exist_ok=True)
|
||||
|
||||
|
||||
def copy_file_robust(src, dst):
|
||||
"""
|
||||
复制单个文件,处理各种坑:
|
||||
- 目标已存在且只读 → 先清除只读属性,否则无法覆盖
|
||||
- 复制到临时文件再替换 → 复制中断不会留下半个文件
|
||||
- copy2 复制元数据(ACL/时间戳)失败 → 退化为只复制内容
|
||||
- 目标不保留只读属性,否则下次备份无法覆盖
|
||||
"""
|
||||
dst_dir = os.path.dirname(dst)
|
||||
if dst_dir and not os.path.isdir(_lp(dst_dir)):
|
||||
os.makedirs(_lp(dst_dir), exist_ok=True)
|
||||
|
||||
if os.path.exists(_lp(dst)):
|
||||
clear_readonly(dst)
|
||||
|
||||
tmp = dst + "~bak"
|
||||
try:
|
||||
if os.path.exists(_lp(tmp)):
|
||||
clear_readonly(tmp)
|
||||
try:
|
||||
os.remove(_lp(tmp))
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
shutil.copy2(_lp(src), _lp(tmp))
|
||||
except OSError:
|
||||
# 元数据复制失败,退化为仅复制内容
|
||||
with open(_lp(src), "rb") as fsrc, open(_lp(tmp), "wb") as fdst:
|
||||
shutil.copyfileobj(fsrc, fdst, BUF_SIZE)
|
||||
clear_readonly(tmp)
|
||||
os.replace(_lp(tmp), _lp(dst))
|
||||
finally:
|
||||
if os.path.exists(_lp(tmp)):
|
||||
try:
|
||||
clear_readonly(tmp)
|
||||
os.remove(_lp(tmp))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def walk_files(root, on_error=None):
|
||||
"""遍历文件,可捕获无法访问目录的错误(不静默跳过)"""
|
||||
for dirpath, dirnames, filenames in os.walk(root, onerror=on_error):
|
||||
# 跳过系统目录(不可读、无意义)
|
||||
dirnames[:] = [d for d in dirnames if d not in SYSTEM_DIRS]
|
||||
for fn in filenames:
|
||||
yield os.path.join(dirpath, fn)
|
||||
|
||||
|
||||
# ==================== 备份引擎 ====================
|
||||
class BackupEngine:
|
||||
def __init__(self, source, dest, progress_callback=None, log_callback=None):
|
||||
self.source = source
|
||||
self.dest = dest
|
||||
self.progress_callback = progress_callback or (lambda p, s: None)
|
||||
self.log_callback = log_callback or (lambda msg: None)
|
||||
self.cancelled = False
|
||||
self.failures = [] # 记录复制失败的相对路径
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled = True
|
||||
|
||||
def _log_error(self, msg):
|
||||
self.failures.append(msg)
|
||||
self.log_callback(f" [失败] {msg}")
|
||||
|
||||
def _on_walk_error(self, e):
|
||||
"""os.walk 无法访问某个目录时调用,避免静默跳过"""
|
||||
self.log_callback(f" 警告: 无法读取目录 {e.filename}: {e.strerror}")
|
||||
|
||||
def _scan(self):
|
||||
"""扫描源目录,返回文件列表"""
|
||||
self.log_callback("[备份] 正在扫描文件...")
|
||||
files = list(walk_files(self.source, on_error=self._on_walk_error))
|
||||
self.log_callback(f"[扫描完成] 共 {len(files)} 个文件")
|
||||
return files
|
||||
|
||||
def _copy_loop(self, all_files, progress_scale):
|
||||
"""复制所有文件,返回 (copied, skipped)"""
|
||||
total = len(all_files)
|
||||
copied_count = 0
|
||||
skipped_count = 0
|
||||
processed = 0
|
||||
|
||||
for src_path in all_files:
|
||||
if self.cancelled:
|
||||
return copied_count, skipped_count
|
||||
|
||||
rel_path = os.path.relpath(src_path, self.source)
|
||||
dst_path = os.path.join(self.dest, rel_path)
|
||||
|
||||
if os.path.exists(_lp(dst_path)) and not files_differ(src_path, dst_path):
|
||||
skipped_count += 1
|
||||
else:
|
||||
try:
|
||||
copy_file_robust(src_path, dst_path)
|
||||
copied_count += 1
|
||||
except (OSError, PermissionError) as e:
|
||||
self._log_error(f"复制失败 {rel_path}: {e}")
|
||||
|
||||
processed += 1
|
||||
if total > 0 and (processed % 10 == 0 or processed == total):
|
||||
self.progress_callback(
|
||||
int(processed / total * progress_scale),
|
||||
f"复制中... {processed}/{total}",
|
||||
)
|
||||
return copied_count, skipped_count
|
||||
|
||||
def full_backup(self):
|
||||
"""全量备份:目标文件夹与源完全一致(镜像同步)"""
|
||||
all_files = self._scan()
|
||||
total = len(all_files)
|
||||
|
||||
# 第一步:遍历源,复制/更新所有文件到目标
|
||||
copied_count, skipped_count = self._copy_loop(all_files, 90)
|
||||
if self.cancelled:
|
||||
self.log_callback("[已取消] 备份中止")
|
||||
return False, {"copied": copied_count, "skipped": skipped_count,
|
||||
"deleted": 0, "failed": self.failures}
|
||||
|
||||
# 第二步:删除目标中存在但源中不存在的条目
|
||||
self.log_callback("[全量备份] 正在清理多余文件...")
|
||||
deleted_count = 0
|
||||
src_set = set()
|
||||
for src_path in all_files:
|
||||
src_set.add(os.path.relpath(src_path, self.source))
|
||||
# 加上源中的目录本身(不含系统目录)
|
||||
for root, dirs, _ in os.walk(self.source):
|
||||
dirs[:] = [d for d in dirs if d not in SYSTEM_DIRS]
|
||||
for name in dirs:
|
||||
src_set.add(os.path.relpath(os.path.join(root, name), self.source))
|
||||
|
||||
to_delete = []
|
||||
for root, dirs, files in os.walk(self.dest, topdown=False):
|
||||
for name in files + dirs:
|
||||
dst_abs = os.path.join(root, name)
|
||||
rel_path = os.path.relpath(dst_abs, self.dest)
|
||||
if rel_path not in src_set:
|
||||
to_delete.append(dst_abs)
|
||||
|
||||
n = len(to_delete)
|
||||
for i, path in enumerate(to_delete):
|
||||
if self.cancelled:
|
||||
self.log_callback("[已取消] 备份中止")
|
||||
return False, {"copied": copied_count, "skipped": skipped_count,
|
||||
"deleted": deleted_count, "failed": self.failures}
|
||||
safe_remove(path)
|
||||
deleted_count += 1
|
||||
if n > 0:
|
||||
self.progress_callback(
|
||||
90 + int(i / n * 10),
|
||||
f"清理中... {i+1}/{n}",
|
||||
)
|
||||
|
||||
self.log_callback(
|
||||
f"[全量备份完成] 复制: {copied_count}, 跳过: {skipped_count}, "
|
||||
f"删除: {deleted_count}, 失败: {len(self.failures)}"
|
||||
)
|
||||
if self.failures:
|
||||
self.log_callback(f"[注意] 有 {len(self.failures)} 项复制失败:")
|
||||
for f in self.failures:
|
||||
self.log_callback(f" {f}")
|
||||
self.progress_callback(100, "完成")
|
||||
return True, {"copied": copied_count, "skipped": skipped_count,
|
||||
"deleted": deleted_count, "failed": self.failures}
|
||||
|
||||
def incremental_backup(self):
|
||||
"""增量备份:只复制新增或修改过的文件,不删除目标中多余文件"""
|
||||
all_files = self._scan()
|
||||
copied_count, skipped_count = self._copy_loop(all_files, 100)
|
||||
if self.cancelled:
|
||||
self.log_callback("[已取消] 备份中止")
|
||||
return False, {"copied": copied_count, "skipped": skipped_count,
|
||||
"deleted": 0, "failed": self.failures}
|
||||
|
||||
self.log_callback(
|
||||
f"[增量备份完成] 复制: {copied_count}, 跳过: {skipped_count}, "
|
||||
f"失败: {len(self.failures)}"
|
||||
)
|
||||
if self.failures:
|
||||
self.log_callback(f"[注意] 有 {len(self.failures)} 项复制失败:")
|
||||
for f in self.failures:
|
||||
self.log_callback(f" {f}")
|
||||
self.progress_callback(100, "完成")
|
||||
return True, {"copied": copied_count, "skipped": skipped_count,
|
||||
"deleted": 0, "failed": self.failures}
|
||||
|
||||
|
||||
# ==================== 应用界面 ====================
|
||||
def resource_path(relative):
|
||||
"""PyInstaller 打包后资源路径"""
|
||||
if hasattr(sys, "_MEIPASS"):
|
||||
return os.path.join(sys._MEIPASS, relative)
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)), relative)
|
||||
|
||||
|
||||
class BackupApp:
|
||||
def __init__(self):
|
||||
self.root = tk.Tk()
|
||||
self.root.title("U盘备份工具")
|
||||
self.root.geometry("640x560")
|
||||
self.root.resizable(True, True)
|
||||
|
||||
# 窗口图标
|
||||
try:
|
||||
ico = resource_path("icon.ico")
|
||||
if os.path.exists(ico):
|
||||
self.root.iconbitmap(ico)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.engine = None
|
||||
self.backup_thread = None
|
||||
self.selected_drive = None
|
||||
self.current_mode = "full"
|
||||
|
||||
self._build_ui()
|
||||
self.refresh_drives()
|
||||
|
||||
def _build_ui(self):
|
||||
# —— 顶部:刷新按钮 + 固定磁盘选项 ——
|
||||
top_frame = ttk.Frame(self.root, padding=10)
|
||||
top_frame.pack(fill=tk.X)
|
||||
|
||||
ttk.Label(top_frame, text="选择要备份的U盘:", font=("", 10, "bold")).pack(
|
||||
side=tk.LEFT
|
||||
)
|
||||
self.var_include_fixed = tk.BooleanVar(value=False)
|
||||
self.chk_fixed = ttk.Checkbutton(
|
||||
top_frame,
|
||||
text="显示固定磁盘\n(读卡器/USB硬盘)",
|
||||
variable=self.var_include_fixed,
|
||||
command=self.refresh_drives,
|
||||
)
|
||||
self.chk_fixed.pack(side=tk.RIGHT, padx=(0, 10))
|
||||
self.btn_refresh = ttk.Button(top_frame, text="刷新列表", command=self.refresh_drives)
|
||||
self.btn_refresh.pack(side=tk.RIGHT)
|
||||
|
||||
# —— U盘列表 ——
|
||||
list_frame = ttk.Frame(self.root, padding=(10, 0))
|
||||
list_frame.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
columns = ("盘符", "卷标", "总容量", "可用空间")
|
||||
self.tree = ttk.Treeview(
|
||||
list_frame, columns=columns, show="headings", selectmode="browse", height=6
|
||||
)
|
||||
self.tree.heading("盘符", text="盘符")
|
||||
self.tree.heading("卷标", text="卷标")
|
||||
self.tree.heading("总容量", text="总容量")
|
||||
self.tree.heading("可用空间", text="可用空间")
|
||||
self.tree.column("盘符", width=70, anchor=tk.CENTER)
|
||||
self.tree.column("卷标", width=150)
|
||||
self.tree.column("总容量", width=110, anchor=tk.CENTER)
|
||||
self.tree.column("可用空间", width=110, anchor=tk.CENTER)
|
||||
self.tree.pack(fill=tk.BOTH, expand=True, side=tk.LEFT)
|
||||
|
||||
scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.tree.yview)
|
||||
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
|
||||
self.tree.configure(yscrollcommand=scrollbar.set)
|
||||
self.tree.bind("<<TreeviewSelect>>", self._on_select)
|
||||
|
||||
# —— 备份模式 ——
|
||||
mode_frame = ttk.Frame(self.root, padding=10)
|
||||
mode_frame.pack(fill=tk.X)
|
||||
|
||||
ttk.Label(mode_frame, text="备份模式:", font=("", 9, "bold")).pack(side=tk.LEFT, padx=(0, 10))
|
||||
self.backup_mode = tk.StringVar(value="full")
|
||||
self.rb_full = ttk.Radiobutton(
|
||||
mode_frame, text="全量备份(镜像同步)", variable=self.backup_mode, value="full"
|
||||
)
|
||||
self.rb_full.pack(side=tk.LEFT, padx=(0, 15))
|
||||
self.rb_inc = ttk.Radiobutton(
|
||||
mode_frame, text="增量备份(仅新增/更新)", variable=self.backup_mode, value="incremental"
|
||||
)
|
||||
self.rb_inc.pack(side=tk.LEFT)
|
||||
|
||||
# —— 目标路径 ——
|
||||
dest_frame = ttk.Frame(self.root, padding=(10, 0))
|
||||
dest_frame.pack(fill=tk.X)
|
||||
ttk.Label(dest_frame, text="备份到:").pack(side=tk.LEFT)
|
||||
self.dest_var = tk.StringVar(value=BACKUP_ROOT)
|
||||
self.dest_entry = ttk.Entry(dest_frame, textvariable=self.dest_var, state="readonly")
|
||||
self.dest_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 5))
|
||||
self.btn_browse = ttk.Button(dest_frame, text="浏览...", command=self._browse_dest)
|
||||
self.btn_browse.pack(side=tk.RIGHT)
|
||||
|
||||
# —— 操作按钮 ——
|
||||
btn_frame = ttk.Frame(self.root, padding=10)
|
||||
btn_frame.pack(fill=tk.X)
|
||||
|
||||
self.btn_backup = ttk.Button(
|
||||
btn_frame, text="开始备份", command=self.start_backup, state=tk.DISABLED
|
||||
)
|
||||
self.btn_backup.pack(side=tk.LEFT, padx=(0, 10))
|
||||
self.btn_cancel = ttk.Button(
|
||||
btn_frame, text="取消", command=self.cancel_backup, state=tk.DISABLED
|
||||
)
|
||||
self.btn_cancel.pack(side=tk.LEFT)
|
||||
|
||||
self.status_label = ttk.Label(btn_frame, text="")
|
||||
self.status_label.pack(side=tk.RIGHT)
|
||||
|
||||
# —— 进度条 ——
|
||||
self.progress = ttk.Progressbar(
|
||||
self.root, mode="determinate", maximum=100
|
||||
)
|
||||
self.progress.pack(fill=tk.X, padx=10, pady=(0, 5))
|
||||
|
||||
# —— 日志 ——
|
||||
log_frame = ttk.Frame(self.root, padding=(10, 0))
|
||||
log_frame.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
ttk.Label(log_frame, text="日志:", font=("", 9, "bold")).pack(anchor=tk.W)
|
||||
self.log_text = tk.Text(log_frame, height=8, state=tk.DISABLED, wrap=tk.WORD)
|
||||
self.log_text.pack(fill=tk.BOTH, expand=True)
|
||||
|
||||
log_scroll = ttk.Scrollbar(log_frame, orient=tk.VERTICAL, command=self.log_text.yview)
|
||||
log_scroll.pack(side=tk.RIGHT, fill=tk.Y)
|
||||
self.log_text.configure(yscrollcommand=log_scroll.set)
|
||||
|
||||
# 底部
|
||||
ttk.Label(
|
||||
self.root, text=f"备份目标: {BACKUP_ROOT}", relief=tk.SUNKEN, anchor=tk.W, padding=2
|
||||
).pack(fill=tk.X)
|
||||
|
||||
def refresh_drives(self):
|
||||
"""刷新 U 盘列表"""
|
||||
self.tree.delete(*self.tree.get_children())
|
||||
self.selected_drive = None
|
||||
self.btn_backup.config(state=tk.DISABLED)
|
||||
|
||||
drives = get_usb_drives(self.var_include_fixed.get())
|
||||
if not drives:
|
||||
self.tree.insert("", tk.END, values=("未检测到U盘", "", "", ""))
|
||||
self.log("未检测到可移动磁盘,请插入U盘后点击刷新。")
|
||||
return
|
||||
|
||||
for d in drives:
|
||||
vol = get_volume_name(d)
|
||||
total, free = get_drive_info(d)
|
||||
self.tree.insert(
|
||||
"",
|
||||
tk.END,
|
||||
values=(d, vol, format_size(total), format_size(free)),
|
||||
)
|
||||
self.log(f"检测到 {len(drives)} 个磁盘,请点击选择。")
|
||||
|
||||
def _on_select(self, event):
|
||||
"""列表选中事件"""
|
||||
sel = self.tree.selection()
|
||||
if sel:
|
||||
item = self.tree.item(sel[0])
|
||||
drive_letter = item["values"][0]
|
||||
if drive_letter and len(drive_letter) == 3 and drive_letter[1] == ":":
|
||||
self.selected_drive = drive_letter
|
||||
self.btn_backup.config(state=tk.NORMAL)
|
||||
self.log(f"已选择: {drive_letter} ({item['values'][1]})")
|
||||
else:
|
||||
self.selected_drive = None
|
||||
self.btn_backup.config(state=tk.DISABLED)
|
||||
|
||||
def _browse_dest(self):
|
||||
path = filedialog.askdirectory(initialdir=BACKUP_ROOT)
|
||||
if path:
|
||||
self.dest_var.set(path)
|
||||
self.log(f"目标路径已更改为: {path}")
|
||||
|
||||
def log(self, msg):
|
||||
self.log_text.config(state=tk.NORMAL)
|
||||
self.log_text.insert(tk.END, msg + "\n")
|
||||
self.log_text.see(tk.END)
|
||||
self.log_text.config(state=tk.DISABLED)
|
||||
|
||||
def update_progress(self, value, status_text):
|
||||
self.root.after(0, lambda: self._update_progress_safe(value, status_text))
|
||||
|
||||
def _update_progress_safe(self, value, status_text):
|
||||
self.progress["value"] = value
|
||||
self.status_label.config(text=status_text)
|
||||
|
||||
def start_backup(self):
|
||||
if not self.selected_drive:
|
||||
messagebox.showwarning("提示", "请先选择一个U盘")
|
||||
return
|
||||
|
||||
if not os.path.exists(self.selected_drive):
|
||||
messagebox.showerror("错误", f"磁盘 {self.selected_drive} 不存在或已拔出!")
|
||||
self.refresh_drives()
|
||||
return
|
||||
|
||||
# 备份开始后锁定模式,避免用户中途切换
|
||||
self.current_mode = self.backup_mode.get()
|
||||
dest_base = self.dest_var.get()
|
||||
|
||||
# 目标子目录: 以卷标+盘符命名
|
||||
vol = get_volume_name(self.selected_drive)
|
||||
letter = self.selected_drive[0]
|
||||
folder_name = f"{letter}盘_{vol}" if vol else f"{letter}盘"
|
||||
dest_path = os.path.join(dest_base, folder_name)
|
||||
|
||||
ensure_dir(dest_path)
|
||||
|
||||
mode_text = "全量备份(镜像同步)" if self.current_mode == "full" else "增量备份"
|
||||
self.log(f"{'='*50}")
|
||||
self.log(f"开始{mode_text}")
|
||||
self.log(f" 源: {self.selected_drive}")
|
||||
self.log(f" 目标: {dest_path}")
|
||||
self.log(f"{'='*50}")
|
||||
|
||||
self.progress["value"] = 0
|
||||
self.status_label.config(text="准备中...")
|
||||
self.btn_backup.config(state=tk.DISABLED)
|
||||
self.btn_cancel.config(state=tk.NORMAL)
|
||||
self.btn_refresh.config(state=tk.DISABLED)
|
||||
|
||||
self.engine = BackupEngine(
|
||||
source=self.selected_drive,
|
||||
dest=dest_path,
|
||||
progress_callback=self.update_progress,
|
||||
log_callback=lambda msg: self.root.after(0, self.log, msg),
|
||||
)
|
||||
|
||||
self.backup_thread = threading.Thread(target=self._run_backup, daemon=True)
|
||||
self.backup_thread.start()
|
||||
|
||||
def _run_backup(self):
|
||||
try:
|
||||
if self.current_mode == "full":
|
||||
success, stats = self.engine.full_backup()
|
||||
else:
|
||||
success, stats = self.engine.incremental_backup()
|
||||
except Exception as e:
|
||||
self.root.after(0, lambda: self.log(f"[错误] {e}"))
|
||||
success = False
|
||||
|
||||
self.root.after(0, lambda: self._backup_done(success))
|
||||
|
||||
def _backup_done(self, success):
|
||||
self.btn_backup.config(state=tk.NORMAL)
|
||||
self.btn_cancel.config(state=tk.DISABLED)
|
||||
self.btn_refresh.config(state=tk.NORMAL)
|
||||
self.engine = None
|
||||
self.backup_thread = None
|
||||
if success:
|
||||
self.status_label.config(text="备份完成")
|
||||
else:
|
||||
self.status_label.config(text="已取消")
|
||||
|
||||
def cancel_backup(self):
|
||||
if self.engine:
|
||||
self.engine.cancel()
|
||||
self.log("[取消中] 正在停止备份...")
|
||||
|
||||
def run(self):
|
||||
self.root.mainloop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = BackupApp()
|
||||
app.run()
|
||||
Reference in new issue
Block a user