Access denied error in serial communications

I am trying to read and write into some serial devices using python serial library, at first it is working fine but whenever I reconnect after disconnecting then “Access denied error is showing”.
Pls help me to resolve this issue.

Please post your code (preferably a minimal reproducible example) and the full traceback. Don’t use screenshots, instead use triple backticks around your code, like this:

    ```python
    # YOUR CODE GOES HERE
    ```

Please provide the OS that you’re using (e.g. Windows 11), Python version and architecture (e.g. Python 3.10, x64), and the version and name of the “python serial library” that you’re using (e.g. pySerial 3.5). Also, please try to provide a minimal example that reproduces the problem.

import serial

ser = serial.Serial(
    port="COM4",
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
    )

command = "0x2E 0x09 \n"
ser.write(serial.to_bytes(command.encode()))
ser.close()

OS: Windows 10
Python Version and architecture : 3.9.6, x64
python serial version: 3.5

python serial version: 0.0.97

Here is your problem. You have installed serial when you need pyserial. Do pip uninstall serial and pip install pyserial.

python serial version: 3.5

I see you changed it. Make sure you don’t have both installed in the same environment, since their names collide.

I used “pip list” → it showed serial version 0.0.97 in command prompt

but below code showed version 3.5

print(serial.__version__)

PS: with pip I only installed pyserial not serial

OK, sounds good. Then we need to see the traceback you get when you get the access denied error.

You mentioned that it works fine “at first” but not when reconnecting. Does that mean that the code you posted above runs OK once only and fails when you run it again?

Most of the time yes, but sometime it fails at first also. When I unplug the serial cable and then re-plug it, works again for 1 to 2 times.
Which one I should uninstall “serial” or “pyserial”, because with “pip list” command I can see both listed.
I uninstalled “serial” and now serial.Serial() function is giving error.

You should only have pyserial installed, not serial. The serial package deals with data serialization, which is not relevant for your use case. pyserial handles serial connections.

Still waiting for that traceback.

I uninstalled serial and got below issue

>>>import serial
>>> ser = serial.Serial()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'serial' has no attribute 'Serial'
>>> dir(serial)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>>

Seems like serial.Serial() is not in pyserial

Seems like serial.Serial() is not in pyserial

It is: pySerial API — pySerial 3.4 documentation

>>> dir(serial)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']

That doesn’t look like either serial or pyserial. Do you perchance have a file called serial.py in your working directory?

No I don’t have any file in my working directory named serial.py

Can you provide me the SOP for the serial communications in python. I need to make it a robust solution so that it won’t create any problem in future also.

Well, that depends on what type of device(s) you are connecting to, and how you are connecting to them. The code you posted above looks OK and should work, the only issue I see with it is that you have hardcoded the port name (“COM4”). The port name is set by the operating system when the device is detected, and may be different every time you connect it.

Another thing is that you don’t need to specify parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, since those are the default values.

Are you using a USB to serial adapter? If so, it might be a good idea to try to autodetect the correct port via the adapter’s USB VID and USB PID (vendor and product ID). You can use serial.tools.list_ports for this:

def autodetect_port():
    USB_VID, USB_PID = 0x04D8, 0x00DF  # These values are just examples, yours will be different.
    port_info_generator = list_ports.grep(f"({USB_VID:04x}:{USB_PID:04x})")
    for port_info in port_info_generator:
        try:
            return serial.Serial(port=port_info.device, baudrate=9600)
        except SerialException:
            pass
    raise SerialException("Device not found")

This won’t work if you’re using a real serial bus directly, such as the UART pins on a raspberry pi for example. You can try to use port_info.hwid instead in that case, but many devices do not specify it.

serial.Serial can be used as a context manager. This is a good idea for brief connections that do not need to persist for long periods of time:

command = "0x2E 0x09 \n"
# Instead of doing this:
ser = serial.Serial(port="COM4", baudrate=9600)
ser.write(serial.to_bytes(command.encode()))
ser.close()
# Do this instead:
with serial.Serial(port="COM4", baudrate=9600) as ser:
    ser.write(serial.to_bytes(command.encode()))
# No need to close the connection manually, the context manages does it for you.

Those are some general suggestions.

Serial devices in Windows are exclusive devices, which means they can only be opened once. Trying to open a serial device that’s already open will fail with an access-denied error. One thing to look out for is duplicate handles, e.g. from calling WinAPI DuplicateHandle(). A kernel file object doesn’t get closed until all handles to it have been closed.

Before running the code I make sure the port name from device manager which is COM4 every time so this is not the issue.
I am using RS232 to USB cable to communicate, target device is RS232 and host-PC is USB.

Problem Solved !
There are 3 library for serial in python
1.) serial
2.) pyserial
3.) pySerial

I uninstalled the python then reinstall it, after reinstalling I only downloaded “serial” and “pySerial” using “pip” and it worked.
Seems like pySerial and pyserial are two different things which were messing with each other.

No, this is not correct. Pip is not case sensitive. pyserial and pySerial are the same thing.

Once again, serial has nothing to do with serial buses. It does not coexist well with pyserial because they share the same import name. Do not install both in the same environment. Doing so is likely the cause of the weird errors you saw earlier.

I used
pip install pyserial
pip install pySerial

No error was given and installed successfully. Is there anything I am missing?