本文介绍了如何监控USB设备的插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在插入USB设备时,我正在尝试监视它们。
我肯定可以使用的测试脚本失败了。

I am trying to monitor for USB devices when they get plugged in.A couple of test scripts fail that I am pretty sure should of worked.

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

^^不执行任何操作。没有错误,没有输出。

^^Does nothing. No error, no output.

我尝试

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

dbus blocks me on both Linux Mint and a Pi3

如何在python3中监视USB设备?

How do I monitor for USB devices in python3?

推荐答案

pyudev 访问Linux udevadm 工具。使用此设备,通过 udevadm监视器

pyudev accesses the linux udevadm tool. with this device attach / detach events are monitored with udevadm monitor

监视连接/分离事件如果调用 udevadm monitor 与python子进程调用?

what happens if you invoke udevadm monitor with python subprocess call ?

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

如果使用pyudev中的 MonitorObserver 会发生什么?

what happens if you use MonitorObserver from pyudev ?

您是否尝试过以root身份调用python(script)?

have you tried to invoke python ( script ) as root ?

以下两种变体在没有root的情况下对我有效,并以具有 -i 选项的脚本:

the following two variants are working for me without root and invoked as script with -i option :

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

这篇关于如何监控USB设备的插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 12:35