Search code examples
pythonlinuxraspberry-piusbpyudev

How to detect USB on Raspberry Pi and access it using Python?


I want to detect USB on Raspberry Pi and access USB to copy some data. I used pyudev and get some info from USB but I can't access it. What should I do? This is my code:

import pyudev
context = pyudev.Context()
for device in context.list_devices(subsystem='block', DEVTYPE='disk'):
    for props in device.properties:
        if device.get("ID_BUS") == "usb":
            print(props, device.get(props))

The path of the USB is /media/pi/CCCOMA_X64FRE_EN-GB_DV9 but I don't find it in list properties, when I print them out. How can I fix it? Thanks.


Solution

  • The reason that you can't find the mount point of the usb drive is that device.properties doesn't include the mount point. You could however get the disk name (/dev/sdx) from device.properties and then use subprocess.check_output(['findmnt', '/dev/sdx1', '-no', 'TARGET']) you can find your mount point in the return of this function.