【问题标题】:Obtain device path from pyudev with python使用python从pyudev获取设备路径
【发布时间】:2016-09-19 18:22:53
【问题描述】:

使用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 之类的路径?

【问题讨论】:

    标签: python usb glib pyudev


    【解决方案1】:

    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 added 事件,该事件将具有 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')]

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

    【讨论】:

      【解决方案2】:

      我找到了这个解决方案:

      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
      

      我知道……太可怕了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-07
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 2019-10-06
        • 2018-04-03
        • 1970-01-01
        相关资源
        最近更新 更多