如何监控USB设备的插入?



我正在尝试监视USB设备何时插入。 几个测试脚本失败了,我很确定应该工作。

import pyudev
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
for device in iter(monitor.poll, None):
if device.action == 'add':
print('{} connected'.format(device))

^^什么都不做。没有错误,没有输出。

我尝试

import dbus
bus = dbus.SystemBus()
obj = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
obj.GetDevices()

输出以下错误:

Traceback (most recent call last):
File "crap.py", line 4, in <module>
obj.GetDevices()
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 70, in __call__
return self._proxy_method(*args, **keywords)
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 145, in __call__
**keywords)
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 651, in call_blocking
message, timeout)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownMethod: No such interface '(null)' on object at path /org/freedesktop/NetworkManager

dbus在Linux Mint和Pi3上都阻止了我

如何在 python3 中监控 USB 设备?

pyudev访问 Linuxudevadm工具。 使用此设备,连接/分离事件通过udevadm monitor进行监视

如果使用 Python 子进程调用调用udevadm monitor会发生什么?

from subprocess import call
call(["udevadm","monitor"])

如果您使用来自 Pyudev 的MonitorObserver会怎样?

您是否尝试过调用 python(脚本(作为根?

以下两个变体在没有root的情况下为我工作,并使用-i选项作为脚本调用:

from pyudev import Context, Monitor
context = Context()
monitor = Monitor.from_netlink(context)
device = monitor.poll(timeout=None)
if device:
print('{0.action}: {0}'.format(device))

-

from pyudev import Context, Monitor, MonitorObserver
context = Context()
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
def print_device_event(device):
print('background event {0.action}: {0.device_path}'.format(device))
observer = MonitorObserver(monitor, callback=print_device_event, name='monitor-observer')
observer.daemon
observer.start()

你可以使用USBMonitor,当你在Linux系统上运行时,它实际上充当pyudev的包装器。

您应该安装它

pip install usb-monitor

然后只需触发监视器守护进程,就像使用 pyudev 一样

from usbmonitor import USBMonitor
# Define the `on_connect` function
on_connect = lambda device_id, device_info: print('{} connected'.format(device_id))
# Create the Monitor instance
monitor = USBMonitor()
# Start the daemon
monitor.start_monitoring(on_connect=on_connect, on_disconnect=None)

它应该避免你遇到一些像这样的低级问题,顺便说一下,也避免了操作系统依赖性。

相关内容

  • 没有找到相关文章

最新更新