python 如何监控usb设备插入?

q3aa0525  于 2023-04-04  发布在  Python
关注(0)|答案(2)|浏览(239)

我试图监视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设备?

muk1a3rh

muk1a3rh1#

pyudev访问linux udevadm工具。使用此设备,连接/分离事件用udevadm monitor监视
如果你用python子进程调用udevadm monitor会发生什么?

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

如果你从pyudev使用MonitorObserver会发生什么?
你有没有试过以root身份调用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()
e4yzc0pl

e4yzc0pl2#

您可以使用USBMonitor,实际上,当您在Linux系统上运行时,它充当pyudev的 Package 器。
您应该使用

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)

它应该可以避免一些像这样的低级问题,顺便说一下,也可以避免对操作系统的依赖。

相关问题