Search code examples
pythonlabelextractusb-driveblkid

extract the usb name from 'blkid' output


I want to extract the usb lable attached to my linux system. I have written some code in python, it works fine, but I want it to be less complicated. Any ideas ... Thanks.

Here is the code:

 #!/usr/bin/env python

 import commands

 import os

 str1=commands.getoutput('sudo blkid')

 name=str1.splitlines()

 for x in range(len(name)):

 if '/dev/sd' in name[x]:

 print name[x]

 str2=name[x].split(" ")

 print str2

 for y in range(len(str2)):

 if 'LABEL' in str2[y]:

 print str2[y]

 str3=str2[y].split('=')

 print str3

 for z in range(len(str3)):

    if 'LABEL' in str3[z]:
            print str3[z+1]

Solution

  • You can use the options on blkid to simplify your task. In this case the -s to specify that you are only interested in the LABEL.

    Then you can find the value of that by reverse searching for the = character, like so:

    out = commands.getoutput('sudo blkid -s LABEL')
    lines = out.splitlines()
    for line in lines:
         if 'dev/sd' in line:
             index = line.rfind('=')
             param = line[index + 1:]
             print param