我想要创建一个脚本来检测一旦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上工作,因为我试图安装这个包,但它并不存在。
发布于 2020-02-02 11:50:09
我解决了我的问题,我写了这个脚本,让我可以检测最后一个可移动的设备是插入的。
代码:
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))发布于 2020-02-01 07:49:00
试试这个
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中提取的
发布于 2022-11-07 15:36:19
我编写了一个Python脚本,用于侦听特定设备并在连接时执行操作,例如:
pip install udev_monitor
udev_monitor.py --devices 0665:5161 --filters=usb --action /root/some_script.sh您可以找到完整的源代码这里。
当然,使用udev,这只适用于Linux。
https://stackoverflow.com/questions/60014591
复制相似问题