问题描述
使用pydev和python-2.7
,我希望获得所连接设备的设备路径.
Using pydev with python-2.7
, I wish obtain the device path of connected devices.
现在我使用此代码:
from pyudev.glib import GUDevMonitorObserver as MonitorObserver
def device_event(observer, action, device):
print 'event {0} on device {1}'.format(action, device)
但是device
返回这样的字符串:
but device
return a string like this:
如何获取类似/dev/ttyUSB1
的路径?
推荐答案
Device(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2')
是 USB设备(即device.device_type == 'usb_device'
).在进行枚举时,/dev/tty*
文件尚不存在,因为稍后会在其自身枚举期间将其分配给其 child USB接口.因此,您需要为Device(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2:1.0')
等待一个单独的 device 添加事件,该事件将具有device.device_type == 'usb_interface'
.
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'
.
然后您可以在其device_added()
中执行print [os.path.join('/dev', f) for f in os.listdir(device.sys_path) if f.startswith('tty')]
:
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()
这篇关于使用python从pyudev获取设备路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!