问题描述
我编写了以下代码,以尝试检测是否通过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 ")
。
我在做什么错了?
解决方法
我发现pydbus D总线绑定更易于使用。
例如,获取其中具有*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
您可以通过以下代码进行操作:
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