gpt4 book ai didi

python - 如何使用python检测USB设备是否插入?

转载 作者:行者123 更新时间:2023-12-02 08:53:21 24 4
gpt4 key购买 nike

我想创建一个脚本来检测 USB 驱动器插入计算机后的情况,现在只需在 cmd 检测 中进行打印。

注意,我在搜索后使用的是 Windows,我发现我需要使用 pyudev 包才能与串行端口通信,并且我需要知道 USB 设备的供应商 ID。

我尝试编写以下代码:

import pyudev
context = pyudev.Context()
monitor = Monitor.from_netlink()
# For USB devices
monitor.filter_by(subsystem='usb')
# OR specifically for most USB serial devices
monitor.filter_by(subsystem='tty')
for action, device in monitor:
vendor_id = device.get('ID_VENDOR_ID')

if vendor_id in ['USB\\VID_0930&PID_6544&REV_0100'] or vendor_id in ['USB\\VID_0930&PID_6544']:
print ('Detected {0} for device with vendor ID {1}'.format(action, vendor_id))

但是系统崩溃并显示此错误:

import fcntl ModuleNotFoundError: No module named 'fcntl'

我认为 fcntl 只能在 Ubuntu 上工作,因为我尝试安装该软件包,但它不存在。

最佳答案

我解决了我的问题,我编写了这个脚本,它允许我检测最后插入的可移动设备。

代码:

import win32api
import win32file

# Returns a list containing letters from removable drives
drive_list = win32api.GetLogicalDriveStrings()
drive_list = drive_list.split("\x00")[0:-1] # the last element is ""
for letter in drive_list:
if win32file.GetDriveType(letter) == win32file.DRIVE_REMOVABLE:# check if the drive is of type removable
print("list drives: {0}".format(letter))

关于python - 如何使用python检测USB设备是否插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60014591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com