[英]How to detect if USB device is plugged in using python?
我想创建一个脚本来检测 USB 驱动器是否插入计算机,现在只是在 cmd detect 中打印。
注意我在搜索后使用 windows 我发现我需要使用pyudev 包才能与串口通信,我需要知道 USB 设备的供应商 ID。
我尝试编写以下代码:
import pyudev
context = pyudev.Context()
monitor = Monitor.from_netlink()
# For USB devices
monitor.filter_by(susbsytem='usb')
# OR specifically for most USB serial devices
monitor.filter_by(susbystem='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 win32file
def locate_usb():
drive_list = []
drivebits = win32file.GetLogicalDrives()
for d in range(1, 26):
mask = 1 << d
if drivebits & mask:
# here if the drive is at least there
drname = '%c:\\' % chr(ord('A') + d)
t = win32file.GetDriveType(drname)
if t == win32file.DRIVE_REMOVABLE:
drive_list.append(drname)
return drive_list
代码实际上取自https://mail.python.org/pipermail/python-win32/2006-December/005406.html
我解决了我的问题,我写了这个脚本,它允许我检测插入的最后一个可移动设备。
代码:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.