2

使用 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/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2')

我怎样才能获得这样的路径/dev/ttyUSB1

4

2 回答 2

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()
于 2016-10-06T00:57:10.283 回答
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

我知道……太可怕了。

于 2016-10-06T13:34:31.313 回答