How to get volume label based on device name using Python
I am making something like a list of mounted devices for Linux.
On program startup I parse /etc/mtab for existing mounts. To get notified about new mounts added to the system am using DBus and in message I get there is volume.label property. Is there any way to get volume label based on device name like /dev/sda1 or /dev/sdd?
Edit:
After some time I managed to find a solution to this problem. Python gio
module has a class named VolumeMonitor. So getting the list with nice names and correct icons is simple as iterating through result of get_mounts()
method:
for mount in volume_monitor.get_mounts():
print moun开发者_高级运维t.get_name(), mount.get_icon()
You can also get a list of drives and volumes. You can also connect some signals and update list appropriately. One note though. Volume is the first one to appear in the list and first to trigger its own events, mounts come later. So if you wish to maintain a list of active mounts, listen to mount-added
and mount-removed
signals instead of volume-added
and volume-removed
.
Instead of using the e2label
command, you can use blkid
and then parse its output:
$ blkid -o value -s LABEL /dev/sda1
/boot
The e2label
command will tell you the volume label when used like this:
e2label /dev/sda1
Note: this only works for ext2, ext3, or ext4 filesystems.
From Python, you can invoke the command with os.system
or Popen
精彩评论