Access USB device info with ctypes?
Question: I am using python with `ctypes` to somehow access information about a USB
device that is connected to the PC. Is this achievable from a .dll? I try to
find things like where it's mounted, its vendor, etc.

An example:

    
    
    >>> import ctypes import windll
    >>> windll.kernel32
    <WindDLL 'kernel32', handle 77590000 at 581b70>
    

But how do I find which .dll is the right one? I googled around but there
doesn't seem to be anything.


Answer: In the end I used a simpler methodology.

I use the `winreg` module that ships with Python to get access to the Windows
registry. `HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices` keeps track of all
devices mounted (currently connected or not). So I get all the device
information from there and to check if the device is currently connected I
simply `os.path.exists` the storage letter of the device (ie. `G:`). The
storage letter can be obtained from the key `MountedDevices`.

Example:

    
    
    # Make it work for Python2 and Python3
    if sys.version_info[0]<3:
        from _winreg import *
    else:
        from winreg import *
    
    # Get DOS devices (connected or not)
    def get_dos_devices():
        ddevs=[dev for dev in get_mounted_devices() if 'DosDevices' in dev[0]]
        return [(d[0], regbin2str(d[1])) for d in ddevs]
    
    # Get all mounted devices (connected or not)
    def get_mounted_devices():
        devs=[]
        mounts=OpenKey(HKEY_LOCAL_MACHINE, 'SYSTEM\MountedDevices')
        for i in range(QueryInfoKey(mounts)[1]):
            devs+=[EnumValue(mounts, i)]
        return devs
    
    # Decode registry binary to readable string
    def regbin2str(bin):
        str=''
        for i in range(0, len(bin), 2):
            if bin[i]<128:
                str+=chr(bin[i])
        return str
    

Then simply run:

    
    
    get_dos_devices()
    

