使用 python 从 pyudev 获取设备路径

Obtain device path from pyudev with python

将pydev与python-2.7一起使用,我希望获得连接设备的设备路径。

现在我使用这个代码:

from pyudev.glib import GUDevMonitorObserver as MonitorObserver

def device_event(observer, action, device):
    print 'event {0} on device {1}'.format(action, device)

但是 device return 这样的字符串:

(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2')

如何获得像 /dev/ttyUSB1 这样的路径?

Device(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2')USB 设备(即 device.device_type == 'usb_device')。在枚举时,/dev/tty* 文件尚不存在,因为稍后在其自身期间将其分配给其 child USB 接口枚举。因此,您需要等待单独的 device added 事件 Device(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2:1.0') 会有 device.device_type == 'usb_interface'.

然后你可以在 device_added() 中做 print [os.path.join('/dev', f) for f in os.listdir(device.sys_path) if f.startswith('tty')]:

import os
import glib
import pyudev
import pyudev.glib

context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
observer = pyudev.glib.GUDevMonitorObserver(monitor)

def device_added(observer, device):
    if device.device_type == "usb_interface":
        print device.sys_path, [os.path.join('/dev', f) for f in os.listdir(device.sys_path) if f.startswith('tty')]

observer.connect('device-added', device_added)
monitor.start()

mainloop = glib.MainLoop()
mainloop.run()

我找到了这个解决方案:

def device_event (observer, action, device):
    if action == "add":
        last_dev = os.popen('ls -ltr /dev/ttyUSB* | tail -n 1').read()
        print "Last device: " + last_dev

我知道……太可怕了。