如何使用Python检测Windows中的闪存驱动器插件?
我想让我的 Windows 计算机在检测到已插入具有特定名称(例如“我的驱动器”)的闪存驱动器时运行 Python 脚本。
我怎样才能实现这一点?
我应该在 Windows 中使用某些工具还是有办法编写另一个 Python 脚本来在插入闪存驱动器后立即检测它是否存在? (如果脚本在计算机上,我会更喜欢它。)
(我是编程新手..)
I want to make my Windows computer run a Python script when it detects that a flash drive which has a particular name (for example "My drive") has been plugged in.
How can I achieve this?
Should I use some tool in Windows or is there a way to write another Python script to detect the presence of a flash drive as soon as it is plugged in? (I'd prefer it if the script was on the computer.)
(I'm a programming newbie.. )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
基于“CD”方法,如果您的脚本枚举了驱动器列表,等待 Windows 分配驱动器号几秒钟,然后重新枚举该列表,会怎么样? python 集可以告诉你发生了什么变化,不是吗?以下对我有用:
Building on the "CD" approach, what if your script enumerated the list of drives, waited a few seconds for Windows to assign the drive letter, then re-enumerated the list? A python set could tell you what changed, no? The following worked for me:
虽然您可以使用“inpectorG4dget”建议的类似方法,但这会非常低效。
为此,您需要使用 Win API。此页面可能对您有用:链接
要在 python 中使用 Win API,请查看此链接:链接
Though you can use a similar method as 'inpectorG4dget' suggested but that will be a lot inefficient.
You need to use Win API for this. This page might be of use to you: Link
And to use Win API's in python check this link out: Link
好吧,如果您使用的是 Linux 发行版,那么 SO 上的这个问题就会有答案。
我可以为你的问题想出一个迂回(不优雅)的解决方案,但至少它会起作用。
每次将闪存驱动器插入 USB 端口时,Windows 操作系统都会为其分配一个驱动器号。为了讨论的目的,我们将该字母称为“F”。
此代码查看我们是否可以 cd 进入
f:\
。如果可以 cd 到f:\
,那么我们可以得出结论,“F”已被分配为驱动器号,并且假设您的闪存驱动器始终被分配给“F”,我们可以得出结论,您的闪存驱动器已插入。Well, if you're on a Linux distribution, then this question on SO would have the answer.
I can think of a round-about (not elegant) solution for your problem, but at the very least it would WORK.
Every time you insert your flash drive into a USB port, the Windows OS assigns a drive letter to it. For the purposes of this discussion, let's call that letter 'F'.
This code looks to see if we can cd into
f:\
. If it is possible to cd intof:\
, then we can conclude that 'F' has been allocated as a drive letter, and under the assumption that your flash drive always gets assigned to 'F', we can conclude that your flash drive has been plugged in.