Search code examples
pythonpermission-deniedpyserialtty

Pyserial: weird permission denied


I use pyserial to open a serial port in my program. This works fine if I have inserted the USB device prior to starting the program. If however I insert the USB device using execution I get a permission denied error.

My code

import serial, sys

def get_serial_port():
    ser_devs = [dev for dev in os.listdir('/dev') if dev.startswith('ttyAC')]
    if len(ser_devs) > 0:
        return '/dev/'+ser_devs[0]
    return None

while(1):
    port = get_serial_port()
    if port:
        print('Will open port %s' % port)
        ser = serial.Serial(port)

Error:

Inserting the USB device while the program is running gives me the below error

serial.serialutil.SerialException: could not open port /dev/ttyACM0:
                       [Errno 13] Permission denied: '/dev/ttyACM0'

This doesn't make sense to me since it otherwise works. I am in dialgroup and I run python as normal user.

Any idea what is going on?


Solution

  • Continuously trying to open the port finally succeeds after a while actually. So hiding the errors makes it work for the moment:

    while(1):
        port = get_serial_port()
        if port:
            print('Will open port %s' % port)
            try:
                ser = serial.Serial(port, 9600)
                print(ser.readline())
            except:
                pass
    

    This ofcourse is just a hack. The behaviour is still very weird and I am not sure if it's pyserial that is buggy or some other program is interfering with the serial.

    I noticed that as fast as I plug the USB device, modem-manager starts using the serial port for a few seconds:

    ModemMana  851        root 8u  CHR  166,0  0t0  16925693 /dev/ttyACM0
    gmain      851   879  root 8u  CHR  166,0  0t0  16925693 /dev/ttyACM0
    gdbus      851   884  root 8u  CHR  166,0  0t0  16925693 /dev/ttyACM0
    

    I still don't see how this 'bug' could give a Permission denied error though. I would expect in this case a Device busy exception.