Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

usb - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...