Obtain device path from pyudev with python
<p>Using pydev with <code>python-2.7</code>, I wish obtain the device path of connected devices. </p>

<p>Now I use this code:</p>

<pre><code>from pyudev.glib import GUDevMonitorObserver as MonitorObserver

def device_event(observer, action, device):
    print 'event {0} on device {1}'.format(action, device)
</code></pre>

<p>but <code>device</code> return a string like this:</p>

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

<p>How can I obtain a path like <code>/dev/ttyUSB1</code> ?</p>

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

<p>Then you could just do <code>print [os.path.join('/dev', f) for f in os.listdir(device.sys_path) if f.startswith('tty')]</code> in its <code>device_added()</code>:</p>

<pre><code>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()
</code></pre>

python usb glib pyudev