如何监控USB设备的插入?

时间:2018-06-24 06:54:24

标签: python linux usb dbus pyudev

我正在尝试监视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设备?

1 个答案:

答案 0 :(得分:1)

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()