【问题标题】:how can the directory of a usb drive connected to a system be obtained?如何获取连接到系统的U盘目录?
【发布时间】:2014-05-02 04:25:33
【问题描述】:

我需要为我正在制作的一个简单的 USB 大容量存储设备浏览器获取为 USB 驱动器创建的目录的路径(我认为它类似于 /media/user/xxxxx)。谁能建议最好/最简单的方法来做到这一点?我正在使用 Ubuntu 13.10 机器,并将在 linux 设备上使用它。

在 python 中需要这个。

【问题讨论】:

  • 除了解析mount 输出之外,还能想到任何东西。您可以从中获取设备和路径,另请参阅stackoverflow.com/questions/3881449/…
  • @m.wasowski 你能就如何做到这一点提供一个简短的解释/相关问题/链接吗?我既是 python 又是 linux 新手
  • 我现在无法详细说明,否则我会被我的女朋友当场杀死......但如果你愿意,我可以在几个小时内回复你。
  • @m.wasowski 没问题

标签: python path directory usb


【解决方案1】:

这应该让你开始:

#!/usr/bin/env python

import os
from glob import glob
from subprocess import check_output, CalledProcessError

def get_usb_devices():
    sdb_devices = map(os.path.realpath, glob('/sys/block/sd*'))
    usb_devices = (dev for dev in sdb_devices
        if 'usb' in dev.split('/')[5])
    return dict((os.path.basename(dev), dev) for dev in usb_devices)

def get_mount_points(devices=None):
    devices = devices or get_usb_devices() # if devices are None: get_usb_devices
    output = check_output(['mount']).splitlines()
    is_usb = lambda path: any(dev in path for dev in devices)
    usb_info = (line for line in output if is_usb(line.split()[0]))
    return [(info.split()[0], info.split()[2]) for info in usb_info]

if __name__ == '__main__':
    print get_mount_points()

它是如何工作的?

首先,我们将/sys/block 解析为sd* 文件(由https://stackoverflow.com/a/3881817/1388392 提供)以过滤掉USB 设备。 稍后您调用 mount 并仅解析这些设备的行的输出。

当然,它们可能是一些边缘情况,当这不起作用时,可移植性问题等。或者更好的方法来做到这一点。但要了解更多信息,您应该向更有经验的 linux 黑客寻求 SuperUser 或 ServerFault 的帮助。

【讨论】:

  • 你能解释一下dict((os.path.split(dev)[-1], dev)部分和devices = devices or get_usb_devices()吗?
  • 第一个返回 dict,其中键是设备路径的基本名称和此路径(在编写此代码时对调试有用的附加信息位)。 devices = devices or get_usb_devices()devices = devices if devices != None else get_usb_devices()大致相同,意思是如果没有参数或者是None,它应该调用函数去查询设备。我希望它有所帮助。
【解决方案2】:

使用 m.wasowski 代码,可能会发生意外行为:

return [(info.split()[0], info.split()[2]) for info in usb_info]

如果您的 USB 设备名称中有空格字符,这部分代码可能会产生错误。我使用名为“USB DEVICE”的设备得到了这种行为。

info.split()[2]

当它是 media/home/USB DEVICE 时,为我返回了 media/home/USB。

我修改了那部分,所以它是“类型”的创始词,并将该行替换为:

#return [(info.split()[0], info.split()[2]) for info in usb_info]

fullInfo = []
for info in usb_info:
    print(info)
    mountURI = info.split()[0]
    usbURI = info.split()[2]
    print(info.split().__sizeof__())
    for x in range(3, info.split().__sizeof__()):
        if info.split()[x].__eq__("type"):
            for m in range(3, x):
                usbURI += " "+info.split()[m]
            break
    fullInfo.append([mountURI, usbURI])
return fullInfo

【讨论】:

    【解决方案3】:

    我必须修改 @m.wasowski 的代码,使其在 Python3.5.4 上运行,如下所示。

    def get_mount_points(devices=None):
        devices = devices or get_usb_devices()  # if devices are None: get_usb_devices
        output = check_output(['mount']).splitlines()
        output = [tmp.decode('UTF-8') for tmp in output]
    
        def is_usb(path):
            return any(dev in path for dev in devices)
        usb_info = (line for line in output if is_usb(line.split()[0]))
        return [(info.split()[0], info.split()[2]) for info in usb_info]
    

    【讨论】:

      【解决方案4】:

      我不得不进一步修改 @nick-sikrier 和 @m-wasowski 响应来处理 LUKs 加密设备。

      def get_usb_devices():
          sdb_devices = map(os.path.realpath, glob('/sys/block/sd*'))
          usb_devices = (dev for dev in sdb_devices
                         if any(['usb' in dev.split('/')[5],
                                 'usb' in dev.split('/')[6]]))
          return dict((os.path.basename(dev), dev) for dev in usb_devices)
      
      def get_mount_points(
          devices = get_usb_devices()
          fullInfo = []
          for dev in devices:
              output = subprocess.check_output(['lsblk', '-lnpo', 'NAME,MOUNTPOINT', '/dev/' + dev]).splitlines()
          for mnt_point in output:
              mnt_point_split = mnt_point.split(' ', 1)
              if len(mnt_point_split) > 1 and mnt_point_split[1].strip():
                  fullInfo.append([mnt_point_split[0], mnt_point_split[1]])
          return fullInfo
      

      【讨论】:

      • get_usb_devices() 正在为我返回一个空字典,即使 ls /sys/block/ | grep "sd*" 输出 sda 并且有 lsblk -lnpo NAME,MOUNTPOINT /dev/sda* 给出的条目
      【解决方案5】:

      在 python 中执行一个简单的 shell 管道:

      import subprocess
      driver_name = "my_usb_stick"
      
      path = subprocess.check_output("cat /proc/mounts | grep '"+driver_name+"' | awk '{print $2}'", shell=True)
      
      path = path.decode('utf-8') # convert bytes in string
      
      >>> "/media/user/my_usb_stick"
      

      说明

      • /proc/mounts/ :是一个列出所有已安装设备的文件
      • 第一列指定安装的设备。
      • 第 2 列显示安装点。
      • 第 3 列说明文件系统类型。
      • 第 4 列告诉您它是只读 (ro) 还是读写 (rw) 挂载的。
      • 第 5 列和第 6 列是虚拟值,旨在匹配 /etc/mtab 中使用的格式

      更多详情请看这个答案:How to interpret /proc/mounts?

      • grep 返回包含您的驱动程序名称的行

      • awk 返回第二列,也就是安装点,也就是您的路径。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-23
        • 1970-01-01
        • 2021-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多