Dunwitch
Dunwitch

Reputation: 197

Python detect USB drive then assign drive letter?

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?

Upvotes: 3

Views: 3401

Answers (2)

Adrien Plisson
Adrien Plisson

Reputation: 23293

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 of the Windows API. you have to first register for notification using RegisterDeviceNotification() then process the WM_DEVICECHANGE 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 is an example message loop, note that in your case you should not need to create a window, only have a message loop).

Upvotes: 2

kettlepot
kettlepot

Reputation: 11011

You could try compiling that script to an exe and make an autorun file in the USB key which runs the script. Then the script does its things. For the assigning the Z:\ letter thing, I'd suggest using Win32Com (even though I don't know if it can handle this) or use ctypes which will give you control on the windows dlls.

Upvotes: 1

Related Questions