You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Raspberry Pi 4上检测U盘插入、获取路径并通过pyusb列出文件

在Raspberry Pi 4(Python 3.11)上实现U盘检测与文件列表获取

一、检测U盘插入并获取挂载路径

静态检测(一次性扫描)

通过读取系统挂载信息文件/proc/mounts,过滤出U盘对应的挂载路径,适合无需实时监听的场景:

import os

def detect_usb_drives():
    usb_drives = []
    with open('/proc/mounts', 'r') as f:
        for line in f.readlines():
            parts = line.strip().split()
            # 匹配常见U盘文件系统及树莓派默认挂载目录
            if parts[2] in ('vfat', 'ext4', 'ntfs') and '/media/pi/' in parts[1]:
                usb_drives.append({
                    'device': parts[0],
                    'mount_path': parts[1]
                })
    return usb_drives

# 调用示例
usb_devices = detect_usb_drives()
if usb_devices:
    for dev in usb_devices:
        print(f"设备: {dev['device']}, 挂载路径: {dev['mount_path']}")
else:
    print("未检测到U盘")

实时监听插入/拔出事件

如果需要实时感知U盘的插拔动作,可以使用pyudev库(需先安装:pip install pyudev),注意此方法需要root权限运行:

import pyudev
from time import sleep

def monitor_usb_events():
    context = pyudev.Context()
    monitor = pyudev.Monitor.from_netlink(context)
    monitor.filter_by(subsystem='block', device_type='disk')

    for device in iter(monitor.poll, None):
        if device.action == 'add' and device.attributes.get('removable') == b'1':
            # 等待系统完成挂载
            sleep(2)
            usb_devices = detect_usb_drives()
            if usb_devices:
                print(f"U盘插入,挂载路径: {usb_devices[-1]['mount_path']}")
        elif device.action == 'remove':
            print("U盘已拔出")

if __name__ == '__main__':
    monitor_usb_events()

二、列出U盘内的所有文件

注意:pyusb是底层USB设备通信库,不负责文件系统操作,读取U盘文件需通过挂载路径使用标准文件系统库实现:

使用os.walk遍历

import os

def list_usb_files(mount_path):
    file_info_list = []
    for root, _, files in os.walk(mount_path):
        for file in files:
            full_path = os.path.join(root, file)
            stat = os.stat(full_path)
            file_info_list.append({
                'name': file,
                'full_path': full_path,
                'size_bytes': stat.st_size,
                'modified_time': stat.st_mtime
            })
    return file_info_list

# 调用示例
usb_devices = detect_usb_drives()
if usb_devices:
    for dev in usb_devices:
        files = list_usb_files(dev['mount_path'])
        print(f"\n{dev['mount_path']} 内的文件:")
        for f in files:
            print(f"{f['name']} - {f['size_bytes']} bytes")

使用pathlib(更简洁的方式)

from pathlib import Path

def list_usb_files_pathlib(mount_path):
    file_info_list = []
    for item in Path(mount_path).rglob('*'):
        if item.is_file():
            stat = item.stat()
            file_info_list.append({
                'name': item.name,
                'full_path': str(item),
                'size_bytes': stat.st_size,
                'modified_time': stat.st_mtime
            })
    return file_info_list

# 调用示例
usb_devices = detect_usb_drives()
if usb_devices:
    for dev in usb_devices:
        files = list_usb_files_pathlib(dev['mount_path'])
        print(f"\n{dev['mount_path']} 内的文件:")
        for f in files:
            print(f"{f['name']} - {f['size_bytes']} bytes")

注意事项

  • 若U盘为NTFS格式,需先安装驱动:sudo apt install ntfs-3g
  • 实时监听代码需以root权限运行(如sudo python3 your_script.py)
  • 挂载路径可能因系统配置不同有所变化,若/media/pi/下未找到,可检查/mnt/目录或自定义挂载点

内容的提问来源于stack exchange,提问作者Ron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 18:17:41