[Python] How can I detect if a USB device is plugged in using Python?

Discussão em 'Python' iniciado por Stack, Janeiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create a script that detects once the USB drive is plugged into the computer and for now just to print in the cmd detect.

    Note I am using Windows. After my search, I found that I need to use the pyudev package in order to communicate with serial ports, and I need to know the vendor ID of the USB device.

    I tried to wrote the below code:

    import pyudev

    context = pyudev.Context()
    monitor = Monitor.from_netlink()

    # For USB devices
    monitor.filter_by(subsystem='usb')

    # OR specifically for most USB serial devices
    monitor.filter_by(subsystem='tty')
    for action, device in monitor:
    vendor_id = device.get('ID_VENDOR_ID')

    if vendor_id in ['USB\\VID_0930&PID_6544&REV_0100'] or vendor_id in ['USB\\VID_0930&PID_6544']:
    print ('Detected {0} for device with vendor ID {1}'.format(action, vendor_id))


    But the system crashes and displays this error:

    import fcntl ModuleNotFoundError: No module named 'fcntl'


    I think 'fcntl' works only on Ubuntu, because I tried to install the package but it didn't exist.

    Continue reading...

Compartilhe esta Página