1

我编写了下面的代码来尝试检测是否通过 USB 连接了特定设备。我想遍历连接的设备。

def scanCameraInterfaces(self):
    ud_manager_obj = dbus.SystemBus().get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    om = dbus.Interface(ud_manager_obj, 'org.freedesktop.systemd1.Unit')

    try:
        for k, v in om.GetManagedObjects().items():
            print(k)
            print(v)
    except Exception:
        print("No devices found...")

但是,这将始终打印“未找到设备...”。所以我删除了try,所以我可以看到错误。它抛出这个:dbus.exceptions.DbusException: org.freedesktop.DBus.Error.AccessDenied: Rejected send message, 2 matched rules: type="method_call", sender=":1.39" (uid=1000 pid=1009 comm="python3 usbtest.py") interface="org.freedesktop.systemd1.Unit" member="GetManagedObjects" error name="(unset)" request_reply="0" destionation=":1.1" (uid=0 pid=1 comm="/sbin/init splash ")

我究竟做错了什么?

4

2 回答 2

2

我发现pydbus D-Bus 绑定更容易使用。

例如,要获取其中包含*usb*模式的所有单元的列表:

import pydbus
systemd = pydbus.SystemBus().get('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
for units in systemd.ListUnitsByPatterns([], ['*usb*']):
    print(units[0])

要使用 Python 获取所有 systemd1 方法的列表:

  • dir(systemd)

在命令行上:

  • busctl introspect org.freedesktop.systemd1 /org/freedesktop/systemd1
于 2020-09-15T15:57:44.287 回答
0

您可以通过以下代码来做到这一点:

import re
import subprocess
device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb")
devices = []
for i in df.split('\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
            devices.append(dinfo)
print devices

你的输出将是:

[
{'device': '/dev/bus/usb/001/009', 'tag': 'Apple, Inc. Optical USB Mouse [Mitsumi]', 'id': '05ac:0304'},
{'device': '/dev/bus/usb/001/001', 'tag': 'Linux Foundation 2.0 root hub', 'id': '1d6b:0002'},
{'device': '/dev/bus/usb/001/002', 'tag': 'Intel Corp. Integrated Rate Matching Hub', 'id': '8087:0020'},
{'device': '/dev/bus/usb/001/004', 'tag': 'Microdia ', 'id': '0c45:641d'}
]

如果您在 Windows 中工作,您可以尝试:

import win32com.client

wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
    print usb.DeviceID
于 2020-09-15T14:46:01.833 回答