0

I need to get the capacity of a usb pendrive that is unmounted. I'm using pyudev to detect it, but I don't know how to get the capacity. I read some documentation about pyusb, but I haven't found anything of useful. Any idea?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Lews
  • 426
  • 4
  • 9
  • Does this answer your question? [Retrieve USB information using pyudev with device name](https://stackoverflow.com/questions/25494086/retrieve-usb-information-using-pyudev-with-device-name) – TylerH Dec 14 '20 at 19:19
  • No, but maybe I found something on github. [here](https://github.com/mlf-core/system-intelligence/blob/4704382fc291418887d27cac676ecbc29e2a67cf/system_intelligence/hdd_info.py) – Lews Dec 14 '20 at 20:34
  • The answer to the linked question includes code to retrieve, among other things, the capacity of the device via the properties call. – TylerH Dec 14 '20 at 20:41
  • yes I see, but it uses subprocess and I don't want use it. – Lews Dec 15 '20 at 00:26

1 Answers1

0

The following code taken from here works pretty well:

def query_hdd_model() -> t.Dict[str, dict]:
    """Get information about all hard drives."""
    if not HDD:
        return {}
    context = pyudev.Context()
    hdds = {}
    for device in context.list_devices(subsystem='block', DEVTYPE='disk'):
        if any(_ in device.device_path for _ in IGNORED_DEVICE_PATHS):
            continue
        hdd = {'size': device.attributes.asint('size')}
        for device_ in itertools.chain([device], device.ancestors):
            try:
                hdd['model'] = device_.attributes.asstring('model')
                break
            except KeyError:
                hdd['model'] = ''
        hdds[device.device_node] = hdd

the exact line is the following:

    hdd = {'size': device.attributes.asint('size')}
Lews
  • 426
  • 4
  • 9