pythonusbglibpyudev

Obtain device path from pyudev with python


Using pydev with python-2.7, I wish obtain the device path of connected devices.

Now I use this code:

from pyudev.glib import GUDevMonitorObserver as MonitorObserver

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

but device return a string like this:

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

How can I obtain a path like /dev/ttyUSB1 ?


Solution

  • Device(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2') is a USB device (i.e. device.device_type == 'usb_device'). At the time of its enumeration the /dev/tty* file does not exist yet as it gets assigned to its child USB interface later during its own enumeration. So you need to wait for a separate device added event for the Device(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2:1.0') which would have device.device_type == 'usb_interface'.

    Then you could just do print [os.path.join('/dev', f) for f in os.listdir(device.sys_path) if f.startswith('tty')] in its 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()