python-3.xusbpyusbpyudev

How to get the capacity of a usb pendrive?


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?


Solution

  • 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')}