2

EDIT I don't see why this is marked as duplicate given that the identified duplicate requires import of pyudev. Not even close to being a duplicate.

This works but it feels "brute force".

Is there a more Pythonic way to get a list of the available disk device names on Linux.

def get_list_of_available_disk_device_names():
    # device names are prefixed with xvd
    # any alpha characters after the prefix identify the specific device,
    # it is possible that there are numbers after the fourth character
    # https://rwmj.wordpress.com/2011/01/09/how-are-linux-drives-named-beyond-drive-26-devsdz/
    # in this case we are hard coding the limit to an arbitrary 26 so device names do not go beyond z
    # the device name prefix can vary across operating systems.  'xvd' is Xen devices on Linux
    device_name_prefix = 'xvd'
    device_letters = [x[3] for x in os.listdir('/dev') if x.startswith(device_name_prefix) and x[3] in string.lowercase]
    device_letter_alpha_numbers = [string.lowercase.index(device_letter) for device_letter in device_letters]
    next_available_device_number = max(device_letter_alpha_numbers) + 1
    if next_available_device_number > 25: # a is 0, z is 25
        raise Exception('No more devices available')
    return ['xvd{}'.format(string.lowercase[x]) for x in range(next_available_device_number, 25)]

Use:

ubuntu@ip-x-x-x-x:~$ python tmp.py
['xvdg', 'xvdh', 'xvdi', 'xvdj', 'xvdk', 'xvdl', 'xvdm', 'xvdn', 'xvdo', 'xvdp', 'xvdq', 'xvdr', 'xvds', 'xvdt', 'xvdu', 'xvdv', 'xvdw', 'xvdx', 'xvdy']
ubuntu@ip-x-x-x-x:~$
Duke Dougal
  • 24,359
  • 31
  • 91
  • 123
  • something like `next_available_device = next(reversed(sorted(glob.glob('/dev/xvd*'))), 'z')[-1]` – njzk2 Aug 27 '15 at 23:42
  • also `if next_available_device_number > 25:` can never happen, because `device_letter_alpha_numbers` would be empty, and next_... will be 1 – njzk2 Aug 27 '15 at 23:46
  • 1
    See http://stackoverflow.com/questions/15941834/finding-only-disk-drives-using-pyudev and http://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python for linux and windows solutions. A good way could be to run a system command which is platform dependent but fdisk -l /dev/sd? should work on Fedora 14 systems. –  Aug 27 '15 at 23:47

1 Answers1

1

I think this could be adapted to suit.

>>> import os
>>> import os.path
>>> import string
>>> [ 'xvd' + e for e in string.ascii_lowercase if not os.path.exists('/dev/xvd' + e)]
['xvda', 'xvdb', 'xvdc', 'xvdd', 'xvde', 'xvdf', 'xvdg', 'xvdh', 'xvdi', 'xvdj', 'xvdk', 'xvdl', 'xvdm', 'xvdn', 'xvdo', 'xvdp', 'xvdq', 'xvdr', 'xvds', 'xvdt', 'xvdu', 'xvdv', 'xvdw', 'xvdx', 'xvdy', 'xvdz']
Jason
  • 3,777
  • 14
  • 27