Hi
I'm trying to use PySerial and I'm getting "Access Denied". I don't know if this is a bug from PySerial library or I'm doing something totally stupid :-)

Specification:
Windows XP pro SP3
PySerial-2.5.win32 (Installed from binary)
Python 2.7.1 (I know it's a bit old :-))

from serial import Serial, SerialException

class Test(object):
    def __init__(self):
        pass

    def tst_serial(self):
        port = Serial()
        port.port = 3
        port.baudrate = 19200
        port.open()
        port.timeout = 1

        try: port.open()
        except SerialException: pass

        port.close()
        # Up to here everything is fine. NOW

        port.open() # Here is the problem
        port.timeout = 0.50

if __name__ == "__main__":
    t = Test()
    t.tst_serial()

Error that I'm getting is:

could not open port COM4: [Error 5] Access is denied.

I checked the port with Portmon while I was running that script to make sure that the port gets closed and it is.

So somehow try and except to open the already opened port messed up the object. I also tried to destroy the object and create it again and I got the same error.

Does any know if this is a bug or am I doing something wrong.

Thanks

--
Mark

I don't know what your trying to connect to, but here is an example to open a COM, receive data, send data and close.

import serial

#Use the COM port you are trying to use
#also set the baud at object creation
ser = serial.Serial('COM8', baudrate=19200)

#treat like a file object
#can read and readline from
data = ser.read()

#show what we got
print data

#send some data, I usually send a newline too
#don't have too though, depends on what your 
#interfacing with
ser.write("hello world\n")

#close the file like serial object
ser.close()

Also it would help to know what your trying to interface with.

Edited 5 Years Ago by Tech B: n/a

Hi
Tech B, Thanks for your reply.
I've been using serial for around 6 months. The example I showed above is just possibly demonstrating a bug.
The scenario is this:
1. Open the serial port (either with your way or just create Serial() object and then assign the port number)
2. Do the read, write or both
3. Use the Try-Except block to try to open the port that is already opened.
4. Try to read and write -> "Access Denied"
5. Create a new object of Serial again with the same port number
6. Try to read, write or both -> "Access Denied"

Now if you even close the port before opening it again like this (Step 3)

try: ser.open()
except: ser.close()

ser = Serial()
...

The new serial object still gives you "Access Denied" on read or write.

So my question is:
Is it a normal behavior of Serial class and if so please explain why (I just need to know more :-))? or is this a bug?

Thanks in Advance

--
Mark

Looks like I misread your post.

Do you get the same error if you try opening the port my way? If you do, try closing the port in the exception.

I googled a bit, try opening the terminal/cmdprompt with root/admin privs.

Let me know how it goes.

Hi
Thanks for your quick response.
I tried this code (As you said close the port in exception):

from serial import Serial, SerialException
 
class Test(object):
    def __init__(self):
        pass
 
    def tst_serial(self):
        port = Serial()
        port.port = 3
        port.baudrate = 19200
        port.open()
        port.timeout = 1
 
        try: port.open()
        except SerialException: port.close()
 
        #port.close()
        # Up to here everything is fine. NOW
 
        port.open() # Here is the problem
        port.timeout = 0.50
 
if __name__ == "__main__":
    t = Test()
    t.tst_serial()

I still get an exception "Access Denied" on line 20 which is port.open(). I ran the script with Administrator privileged and got the same exception "Access Denied".

Also I don't think it's a privilege problem since the first open on line 11 works fine without any error or exception.

My guess is when I'm trying to open the port that has already been opened, Serial flag an error on that port that causes "Access Denied". But close() function should clear all those flags (errors and exceptions) so that the next open() can open the port, which is not doing it. This only happens in the same script. After running above script I ran a very simple script which does open() and close() on port and no error there which make sense (Garbage Collection).

I ran your script and it works fine on both, admin and non-admin terminal since you are not trying to reopen the port that has already been opened.

Any idea?

--
Mark

What are you trying to connect to? It might be the other device refusing repetitive connections. Try time.sleep() for a second or two and try again. Also, maybe try putting all the port info in the __init__() method, like the timeout and port number and all.

Hi
Thanks for your reply.
I tried what you said and still getting the same error

from serial import Serial, SerialException
from time import sleep
 
class Test(object):
	def __init__(self):
		self.port          = Serial()
		self.port.port     = 3
		self.port.baudrate = 19200
		self.port.timeout  = 1
		
	def re_init(self):
		del self.port
		self.port          = Serial()
		self.port.port     = 3
		self.port.baudrate = 19200
		self.port.timeout  = 1
	
	def tst_serial_1(self):
		self.port.open()
		self.port.close()
		self.port.open()
		self.port.close()
 
	def tst_serial(self):
		self.port.open()
 
		try: self.port.open()
		except SerialException: 
			self.port.close()
 
		print "Sleeping..."
		sleep(10)
        #port.close()
        # Up to here everything is fine. NOW
		
		self.re_init()
		self.port.open() # Here is the problem
		self.port.timeout = 0.50
 
if __name__ == "__main__":
	t = Test()
	print "Testing tst_serial_1"
	t.tst_serial_1()
	
	print "Testing tst_serial"
	t.tst_serial()

I modified my script so that now tests two thing
1. tst_serial_1 -> open - close - open - close (No Error)
2. tst_serial -> Added sleep and still fails ("Access Denied")

I tested on admin and non-admin terminal.
I'm try to send the binary code to some hardware device which is working and with tst_serial_1 scenario I can read and write without any problem.


--
Mark

Can you post the entire trace-back, also add some print statements in each of the try/excepts so we can verify what it is doing.

Something like:

try: 
   self.port.open()
   print "port open"
except SerialException:
   self.port.close()
   print "port closed"

Edited 5 Years Ago by Tech B: n/a

Hi

from serial import Serial, SerialException

from time import sleep

 

class Test(object):

    def __init__(self):
        print "__init__ called"
        
        print "Creating new Serial Object..."
        self.port = Serial()
        print "Done"

        print "Configuring Serial Object (Port)..."
        self.port.port     = 3
        self.port.baudrate = 19200
        self.port.timeout  = 1
        print "Done\nLeaving __init__\n"

		
    def re_init(self):
        print "re_init called"
        del self.port
        print "Deleting port Object completed"

        print "Creating new Serial Object..."
        self.port = Serial()
        print "Done"

        print "Configuring Serial Object (Port)..."
        self.port.port     = 3
        self.port.baudrate = 19200
        self.port.timeout  = 1
        print "Done\nLeaving re_init\n"


    def tst_serial_1(self):
        print "tst_serial_1 called"
        print "Opening Serial Port..."
        self.port.open()
        print "Done"

        print "Closing Serial Port..."
        self.port.close()
        print "Done"

        print "Opening Serial Port..."
        self.port.open()
        print "Done"

        print "Closing Serial Port..."
        self.port.close()
        print "Done\nLeaving tst_serial_1\n"


    def tst_serial(self):
        print "tst_serial called"
        print "Opening Serial Port..."
        self.port.open()
        print "Done"

        print "TRY-EXCEPT Block."
        try: 
            print "Try to reopen Serial Port" 
            self.port.open()
            print "Done"
        except SerialException:
            print "Exception Happened"
            print "Closing Serial Port..."
            self.port.close()
            print "Done"

        print "Sleeping..."
        sleep(10)
        print "Done"

        #port.close()
        # Up to here everything is fine. NOW

        print "Calling re_init()"
        self.re_init()
        print "Done"

        print "Opening Serial Port..."
        self.port.open() # Here is the problem
        print "Done"

        self.port.timeout = 0.50
        print "Done\nLeaving tst_serial\n"

 
if __name__ == "__main__":
    print "Creating Test Object..."
    t = Test()
    print "Done"

    print "Testing tst_serial_1"
    t.tst_serial_1()

    print "Testing tst_serial"
    t.tst_serial()

I hope this helps.

--
Mark

Hi all,

I'd like to join your discussion:

I experienced exactely the same behaviour, but in your last post, Mark, both methods: t.tst_serial() and t.tst_serial_1() returned the described error message (could not open port COM2: when testing COM1).

Can't help it, I'd be thankful on further explanation.

Greets,

Hi everyone,

I'd also like to participate.

I'm currently communicating with an Arduino - I'm very new to Python and Processing codes, so please don't rely solely on my code.

I think that the problem lies in the hardware end of the setup. If you configure the serial ports to open later via the python shell;

>>> ser = serial.Serial()
>>> ser.baudrate = 9200
>>> ser.port = 4
>>> ser
Serial<id=0xa81c10, open=False>(port='COM4', baudrate=9200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
>>> ser.isOpen()
False
>>> ser.open()
SerialException: could not open port COM5: [Error 5] Access is denied.
>>> ser.close()
>>> ser.isOpen()
False
>>> ser.open()
SerialException: could not open port COM5: [Error 5] Access is denied.

it still throws up an access denied error, even though the port is reported to be closed.
I have also closed and reopened the port on the Arduino, but I don't yet know how to check to see whether the port is open or not on that. I'll do that as soon as I've posted this.

I hope I've helped to shed some light on this irritating topic. Good luck to all :D


- Tom

Matzek, so you know people are much less likely to respond to an old thread, it's advised to start your own.

I get the access denied for opening a port in python if I don't run the python script as root.

sudo python program.py

Not sure if this applies/works for everybody, but it solved my problem. ON my linux machine (Raspberry Pi) you need root access to open a port up in python (correct me if I'm wrong).

Edited 4 Years Ago by meistervision: More info

Comments
Good addition to old thread, even OP was in Windows
This article has been dead for over six months. Start a new discussion instead.