如何获得连接到系统的USB驱动器的目录? [英] how can the directory of a usb drive connected to a system be obtained?

查看:131
本文介绍了如何获得连接到系统的USB驱动器的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to obtain the path to the directory created for a usb drive(I think it's something like /media/user/xxxxx) for a simple usb mass storage device browser that I am making. Can anyone suggest the best/simplest way to do this? I am using an Ubuntu 13.10 machine and will be using it on a linux device.

在python中需要它.

Need this in python.

推荐答案

这应该可以帮助您入门:

This should get you started:

#!/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并仅解析那些设备的线路输出.

First, we parse /sys/block for sd* files (courtesy of https://stackoverflow.com/a/3881817/1388392) to filter out usb devices. Later you call mount and parse output for lines only for those devices.

当然,在某些情况下,这可能行不通,可移植性问题等.但是,有关更多信息,您应该与经验丰富的Linux黑客寻求有关SuperUser或ServerFault的帮助.

Of course they might be some edge cases, when this won't work, portability issues etc. Or better ways to do it. But for more information you should rather seek help on SuperUser or ServerFault, with more experienced linux hackers.

这篇关于如何获得连接到系统的USB驱动器的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆