Starting with an absolute file path, I want to obtain the following information:
I am aware that 2 and 3 may be undefined in many cases (e.g. for loopback, ramfs, encyrpted devices), which is totally fine. I also know how to obtain that information using a shell and system tools like df
and the /sys
or /proc
filesystem. See this question for reference.
However, I am searching for the least cumbersone method to do that programmatically with Python 3.5. That means:
/proc
or /sys
(which may be subject to change or depend on kernel configuration?)So far, I am using os.stat()
on the path to get the block device's major and minor number from stat_result.st_dev
. But what's the proper way to proceed?
There is for example
/proc/mounts
/proc/partitions
/sys/dev/block/<major>:<minor>
Notes:
Regarding mounted block devices an partitions, /proc/mounts
and /proc/partitions
seem to be the canonical information source (which is OK). For UUIDs, labels, serials etc. I currently use udevadm
and parse the output:
def get_udev_properties(dev_name):
cmd = ["udevadm", "info", "--query=property", "--name", dev_name]
result = subprocess.run(cmd, stdout=subprocess.PIPE)
return parse_properties(result.stdout)
Further note: Abstracting from my acutal problem, one could ask more general:
This is a script on GitHub I came across earlier today that uses Python to fetch information about drive make and model (and lots of others).
/proc/partitions
holds info on partitions; for more detailed information you'll have either to run a subprocess as you do now, or for example for GPT do the parsing yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With