【问题标题】:How can I fetch all systemd1 devices?如何获取所有 systemd1 设备?
【发布时间】:2020-09-15 14:39:29
【问题描述】:

我编写了下面的代码来尝试检测是否通过 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 ")

我做错了什么?

【问题讨论】:

    标签: python dbus freedesktop.org


    【解决方案1】:

    我发现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

    【讨论】:

      【解决方案2】:

      你可以通过以下代码来实现:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-06
        • 2017-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-11
        • 1970-01-01
        • 2021-05-21
        相关资源
        最近更新 更多