Skip to content
Advertisement

Determine Device of Filesystem in Python

How do you use Python to determine which Linux device/partition contains a given filesystem?

e.g.

>>> get_filesystem_device('/')
/dev/sda
>>> get_filesystem_partition('/')
/dev/sda1

Advertisement

Answer

It is not the purdiest, but this will get you started:

#!/usr/bin/python

import os, stat, subprocess, shlex, re, sys

dev=os.stat('/')[stat.ST_DEV]
major=os.major(dev)
minor=os.minor(dev)

out = subprocess.Popen(shlex.split("df /"), stdout=subprocess.PIPE).communicate()
m=re.search(r'(/[^s]+)s',str(out))

if m:
    mp= m.group(1) 
else:
    print "cannot parse df"   
    sys.exit(2)

print "'/' mounted at '%s' with dev number %i, %i" % (mp,major,minor)   

On OS X:

'/' mounted at '/dev/disk0s2' with dev number 14, 2

On Ubuntu:

'/' mounted at '/dev/sda1' with dev number 8, 1

To get the device name, chop off the minor number from the partition name. On OS X, also chop the ‘s’ + minor number.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement