Python检测USB驱动器然后分配驱动器号? [英] Python detect USB drive then assign drive letter?

查看:45
本文介绍了Python检测USB驱动器然后分配驱动器号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题来了.我们有数百个外部 500GB USB 驱动器.一年中,每次开车都会前往一个新的地点.自动检测 USB 驱动器已插入 Windows 系统,然后分配 Z:\ 驱动器号的最佳方法是什么?这些 USB 驱动器将插入许多不同的计算机,因此脚本如下

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)

由于移动USB驱动器在不同Windows系统上一直是动态的,所以很难使用吗?您可以通过 WMI 自动检测或使用 NTFS 进行某种卷挂载吗?

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?

推荐答案

正如 terabytest 所说,您可以从驱动器根目录中的 autorun.inf 运行脚本.就个人而言,我会使用批处理脚本:

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

%~d0 检索当前正在执行的批处理文件的驱动器号.

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

如果这还不够,可以通过使用 Windows API 的设备管理功能.您必须首先使用 RegisterDeviceNotification 注册通知() 然后处理WM_DEVICECHANGE 事件循环中的消息.不幸的是,这需要一个事件循环,我不知道如何在 python 中轻松创建一个(除了从头开始创建:这里 是一个示例消息循环,请注意,在您的情况下,您不需要创建窗口,只有一个消息循环).

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).

这篇关于Python检测USB驱动器然后分配驱动器号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆