好的,下面我将带你了解如何使用 Python 打造一个专业级的 USB 安全弹出工具。这种工具通常用于确保 USB 驱动器在拔出之前被正确卸载,以避免数据丢失或损坏。
项目概述
我们的目标是创建一个能够:
- 列出系统中的所有 USB 存储设备。
- 安全卸载(弹出)USB 存储设备。
- 提供用户友好的图形界面(GUI)。
二、所需技术
- Python:选择 Python 作为开发语言,方便跨平台且有大量库支持。
psutil
:用于列出系统中的所有存储设备,并管理磁盘的状态。pyudev
:这是一个 Linux 系统下用来监控 USB 设备的库。tkinter
:用于实现图形用户界面 (GUI)。shutil
:用于执行文件系统操作,例如安全卸载。- 跨平台支持:主要支持 Windows 和 Linux 系统。
三、项目步骤
- 获取所有存储设备:
- 需要列出系统中的所有 USB 存储设备,并允许用户选择要弹出的设备。
- 卸载 USB 设备:
- 通过系统命令或 API 来确保设备安全卸载。
- 图形界面:
- 提供用户友好的图形界面,展示设备列表和弹出按钮。
四、Python 安全弹出 USB 工具
1. 安装依赖
首先,安装必需的依赖包:
pip install psutil pyudev
2. 获取 USB 设备列表
我们使用 psutil
和 pyudev
库来获取系统中的所有 USB 存储设备。
获取 USB 设备列表(Windows)
对于 Windows 系统,我们可以使用 psutil
来列出所有的磁盘设备。
import psutil
def list_usb_drives():
# 获取所有磁盘分区信息
partitions = psutil.disk_partitions()
usb_drives = []
for partition in partitions:
# 只选取挂载了 USB 存储的磁盘设备
if 'removable' in partition.opts:
usb_drives.append(partition.device)
return usb_drives
获取 USB 设备列表(Linux)
在 Linux 上,我们使用 pyudev
来监控和列出 USB 设备。
import pyudev
def list_usb_drives():
context = pyudev.Context()
usb_drives = []
for device in context.list_devices(subsystem='block', DEVTYPE='partition'):
if 'usb' in device.device_path:
usb_drives.append(device.device_node)
return usb_drives
3. 安全卸载 USB 设备
我们通过 psutil
和系统命令来执行安全卸载操作。
安全卸载(Windows)
Windows 下可以使用 psutil
的 disk_usage
来确保设备被卸载,但最直接的做法是调用 os
执行安全卸载命令:
import os
def eject_usb(device):
# 这里需要确保 device 是 USB 设备的路径
os.system(f"powershell -Command 'Mount-DiskImage -ImagePath {device} -Eject'")
安全卸载(Linux)
Linux 下,我们使用 umount
命令来卸载设备。
import os
def eject_usb(device):
# 使用 umount 命令卸载设备
os.system(f"umount {device}")
4. 构建图形界面
我们使用 tkinter
来创建图形界面,让用户能够选择设备并执行弹出操作。
import tkinter as tk
from tkinter import messagebox
# 获取 USB 设备
usb_devices = list_usb_drives()
# 创建窗口
root = tk.Tk()
root.title("USB 安全弹出工具")
def eject_device():
selected_device = device_listbox.get(tk.ACTIVE)
if selected_device:
# 调用卸载函数
try:
eject_usb(selected_device)
messagebox.showinfo("成功", f"设备 {selected_device} 已成功弹出")
except Exception as e:
messagebox.showerror("错误", f"无法弹出设备 {selected_device}: {e}")
else:
messagebox.showwarning("警告", "请选择一个设备")
# 显示 USB 设备列表
device_listbox = tk.Listbox(root)
for device in usb_devices:
device_listbox.insert(tk.END, device)
device_listbox.pack(pady=10)
# 安全弹出按钮
eject_button = tk.Button(root, text="安全弹出", command=eject_device)
eject_button.pack(pady=20)
# 运行 GUI
root.mainloop()
五、完整代码
这是一个将所有部分集成在一起的完整代码:
import psutil
import pyudev
import os
import tkinter as tk
from tkinter import messagebox
def list_usb_drives():
"""获取 USB 存储设备列表"""
usb_drives = []
# Windows 获取 USB 设备
if os.name == 'nt':
partitions = psutil.disk_partitions()
for partition in partitions:
if 'removable' in partition.opts:
usb_drives.append(partition.device)
# Linux 获取 USB 设备
elif os.name == 'posix':
context = pyudev.Context()
for device in context.list_devices(subsystem='block', DEVTYPE='partition'):
if 'usb' in device.device_path:
usb_drives.append(device.device_node)
return usb_drives
def eject_usb(device):
"""安全弹出 USB 设备"""
try:
if os.name == 'nt':
# Windows 上使用 PowerShell 命令弹出 USB
os.system(f"powershell -Command 'Mount-DiskImage -ImagePath {device} -Eject'")
elif os.name == 'posix':
# Linux 上使用 umount 命令
os.system(f"umount {device}")
return True
except Exception as e:
print(f"Error ejecting USB: {e}")
return False
# 创建 GUI
def create_gui():
usb_devices = list_usb_drives()
root = tk.Tk()
root.title("USB 安全弹出工具")
def eject_device():
selected_device = device_listbox.get(tk.ACTIVE)
if selected_device:
if eject_usb(selected_device):
messagebox.showinfo("成功", f"设备 {selected_device} 已成功弹出")
else:
messagebox.showerror("错误", f"无法弹出设备 {selected_device}")
else:
messagebox.showwarning("警告", "请选择一个设备")
# 显示 USB 设备列表
device_listbox = tk.Listbox(root)
for device in usb_devices:
device_listbox.insert(tk.END, device)
device_listbox.pack(pady=10)
# 安全弹出按钮
eject_button = tk.Button(root, text="安全弹出", command=eject_device)
eject_button.pack(pady=20)
# 运行 GUI
root.mainloop()
# 启动 GUI
create_gui()
六、功能总结
- USB 设备列表显示:通过
psutil
和pyudev
获取 USB 设备,并在 GUI 中显示。 - 安全卸载:通过执行系统命令来卸载选中的 USB 存储设备。
- 图形界面:使用
tkinter
创建一个简单的用户界面,提供设备选择和弹出按钮。
七、注意事项
- 权限问题:在 Linux 系统中,卸载设备需要管理员权限。在运行脚本时,确保以
root
用户运行或者使用sudo
。 - 设备类型判断:通过
psutil
和pyudev
获取的是设备的路径或分区,某些情况下可能需要更多的设备信息(如设备名等)。 - 跨平台支持:虽然此工具支持 Windows 和 Linux,但在不同平台上可能有不同的命令和权限设置,需要根据实际情况调整。
八、结语
通过这篇教程,你应该能够使用 Python 构建一个简单的 USB 安全弹出工具。这个工具适用于需要频繁拔插 USB 设备的用户,可以确保设备被正确卸载,从而避免数据损坏或丢失。希望你能根据这个基础版本,进一步完善和优化它,加入更多的功能!
发表回复