使用python从pyudev获取设备路径

时间:2016-09-19 18:22:53

标签: python usb glib pyudev

将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会返回一个这样的字符串:

  

(U '/ SYS /设备/ pci0000:00 / pci0000:00:01.0 / 0000.000 / USB1 / 1-2')

如何获得/dev/ttyUSB1之类的路径?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

我找到了这个解决方案:

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

我知道......太可怕了。