Python detect USB drive then assign drive letter?
Question: Here is the problem. We have 100s of external 500gb USB drives. Each drive
will travel to a new location through the year. What is the best way to
automatically detect that a USB drive has been plugged into a Windows system,
then assign a Z:\ drive letter? These USB drives will be plugged into lots of
different computers so a script like this

    
    
    import subprocess
    
    diskpart_data = "z-drive.txt"
    open (diskpart_data, "w").write ("""
    select volume F: 
    assign letter=Z
    """)
    subprocess.call ('diskpart /s %s' % diskpart_data)
    

is hard to use due to the dynamic nature of the mobile USB drive on different
Windows systems all the time? Could you autodetect through WMI or do some kind
of volume mount with NTFS?


Answer: as terabytest said, you may run a script from an autorun.inf in the root of
the drive. personally, i would do with a batch script:

    
    
    (echo select volume %~d0 && echo assign letter=Z) | diskpart
    

the `%~d0` retrieves the drive letter of the currently executing batch file.

if this is not sufficient, there is a way of being informed when a removable
drive is inserted by using the [device management
functions](http://msdn.microsoft.com/en-us/library/aa363224%28VS.85%29.aspx)
of the Windows API. you have to first register for notification using
[`RegisterDeviceNotification()`](http://msdn.microsoft.com/en-
us/library/aa363431%28VS.85%29.aspx) then process the
[`WM_DEVICECHANGE`](http://msdn.microsoft.com/en-
us/library/aa363480%28VS.85%29.aspx) message in the event loop. unfortunately,
this needs an event loop, and i don't know how you can easily create one in
python (apart from creating it from scratch:
[here](http://msdn.microsoft.com/en-us/library/ms644928%28VS.85%29.aspx) is an
example message loop, note that in your case you should not need to create a
window, only have a message loop).

