Search code examples
pythonpathdirectoryusb

how can the directory of a usb drive connected to a system be obtained?


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.

Need this in python.


Solution

  • 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()
    

    How does it work?

    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.

    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.