Starting with an absolute file path, I want to obtain the following information:
- The mount point of the filesystem on which the file is stored (in order to compute the path relative to the mount point)
- The UUID and label of the file system
- The type (or vendor name) and the serial number of the hard drive that contains the partition
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:
- Prefer system calls instead of parsing contents of
/proc
or/sys
(which may be subject to change or depend on kernel configuration?) - Avoid calling subprocesses and parsing their output (the definition of cumbersome)
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:
- What's the canonical identification or representation of a block device with respect to linux system calls and the kernel filesystems?
- What's the proper way to obtain that representation by major and minor number?
- What's the proper way to obtain detailed information about a block device?