get device with mount point

13,996

Solution 1

This is totally unrelated to Ubuntu, but here you are:

#!/usr/bin/env python

import subprocess

mounts = {}

for line in subprocess.check_output(['mount', '-l']).split('\n'):
    parts = line.split(' ')
    if len(parts) > 2:
        mounts[parts[2]] = parts[0]

print mounts

Solution 2

mount | cut -f 1,3 -d ' '

Explanation: cut is a handy little tool for splitting lines using a delimiter character (specified by the -d option) and selecting some of the fields for output (using a comma separated argument list to the -f option). Since the mount output is regular and delimited by spaces, the above outputs the first and third column, omitting "on" and the remainder of the line.

Solution 3

Why not use the Gio interface? I like these solutions better than executing a bash command and parsing its output. This way you can catch exceptions and have more control.

Here's a little example:

>>> from gi.repository import Gio
>>> vm = Gio.VolumeMonitor.get()
>>> for v in vm.get_volumes():
...     print v.get_name()

See the documentation for much more interesting methods.

GVolumeMonitor

GVolume

Gmount

Share:
13,996

Related videos on Youtube

Hairo
Author by

Hairo

Updated on September 18, 2022

Comments

  • Hairo
    Hairo over 1 year

    there's a way to get the device name (/dev/sdx) with the mounted folder? i mean, get the assosiated device in a mount point using the mounted folder as the reference, or make a python dictionary with the mount points : devices...

    i know that mount -l can get me the mounted file system info, but i don't really know how to strip it to make the dictionary...

    any help?

    Regards...

  • Hairo
    Hairo over 11 years
    thank, this did the job, but it's having problems when a tag has a space on it, it only displays the first word...
  • Sergey
    Sergey over 11 years
    The code is just an illustration, I didn't try to write a robust production ready program. You can try using cat /proc/mounts command instead of mount - maybe it's output is easier to parse.
  • Hairo
    Hairo over 11 years
    thanks again, i managed to get it working using cat /proc/mounts and replacing some things with string.replace()
  • January
    January over 11 years
    Why not create a Java app for doing what can be achieved with a 27 character command line? Sorry, couldn't resist.
  • Sergey
    Sergey over 11 years
    @January: Firstly, it's Python :) Secondly, the OP stated she/he needs a Python dictionary, supposedly to be used in an application. Piping the output through cut does not solve the problem of converting the output into something meaningful for a program.
  • January
    January over 11 years
    @Sergey: well, yes, you have a point here. That's why I upped your answer. Nonetheless, I shudder when I see the code above.
  • Hairo
    Hairo over 11 years
    mm... this looks better, i'll try it when i get home :)