How can I listen for 'usb device inserted' events in Linux, in Python?

后端 未结 4 1007
再見小時候
再見小時候 2020-11-27 09:48

I\'d like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, cop

4条回答
  •  没有蜡笔的小新
    2020-11-27 10:40

    Here is a solution in 5 lines.

    import pyudev
    
    context = pyudev.Context()
    monitor = pyudev.Monitor.from_netlink(context)
    monitor.filter_by(subsystem='usb')
    
    for device in iter(monitor.poll, None):
        if device.action == 'add':
            print('{} connected'.format(device))
            # do something very interesting here.
    

    Save this to a file say usb_monitor.py, run python monitor.py. Plug any usb and it will print device details

    → python usb_monitor.py 
    Device('/sys/devices/pci0000:00/0000:00:14.0/usb1/1-6/1-6:1.0') connected
    Device('/sys/devices/pci0000:00/0000:00:14.0/usb1/1-1/1-1:1.0') connected
    

    Tested on Python 3.5 with pyudev==0.21.0.

提交回复
热议问题