How can I get the directory of a USB drive connected to the system?

I need to get the path to the directory created for the USB drive (I think it is something like / media / user / xxxxx) for the simple browser of the usb mass storage device that I am doing. Can anyone suggest a better / easiest way to do this? I am using a Ubuntu 13.10 machine and will use it on a linux device.

This is needed in python.

+4
source share
3 answers

This should help you:

#!/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()

How it works?

/sys/block sd* ( fooobar.com/questions/364972/...), USB. mount .

, , , .. . SuperUser ServerFault Linux.

+10

m.wasowski, :

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

, USB- . "USB DEVICE".

info.split()[2]

//USB , //USB-.

, "type", :

#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
+4

I had to change the @ m.wasowski code to work in Python3.5.4 as follows.

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]
+1
source

Source: https://habr.com/ru/post/1533191/


All Articles