PySerial could not open port COM4: [Error 5] Access is denied - please help

A

Adam

Grant Edwards said:
Because it's already been opened by the Python program.


Pyserial will happily try if you call the open() of a port that's
already open, but Windows will return an error.


Because TeraTerm only opens it once.


That code is broken.

The port is opened by this line:

self.ser=serial.Serial(port='\\.\COM1', baudrate=9600,
bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE, timeout=1)

And then the author tries to _open_it_a_second_time_ here:

self.ser.open()


Like I kept telling you, those programs are trying to re-open a port
that they've already open. Here's the erroneous code:

wattcher.py:

53
54 # open up the FTDI serial port to get data transmitted to xbee
55 ser = serial.Serial(SERIALPORT, BAUDRATE)
56 ser.open()
57

Line 55 opens the serial port.

Line 56 tries to _open_it_again_. _The_port_is_already_open_.
Windows doesn't allow a serial port to be opened twice, therefore the
ser.open() call raises an exception.

Just delete line 56.


The same thing happens here:

gmeter-wattcher.py

83
84 # open up the FTDI serial port to get data transmitted to xbee
85 ser = serial.Serial(SERIALPORT, BAUDRATE)
86 ser.open()
87

Just delete line 86.

See how simple it was to get the problem solved once you posted the
actual code?


Thanks, Grant !
 
A

Adam

Roel Schroeven said:
Temia Eszteri schreef:

That doesn't have anything to do with Windows, but with how pySerial
works. See the documentation for __init__():

"The port is immediately opened on object creation, when a port is given.
It is not opened when port is None and a successive call to open() will be
needed."

So if your script does something like

prt = serial.Serial('COM4')

then pySerial automatically opens the port, and you shouldn't call
prt.open() anymore.

If, on the contrary, you do something like

prt = serial.Serial()
prt.port = 'COM4'

then pySerial doesn't open the port, and you have to call prt.open() to do
it.

PySerial has this same behavior on both Windows and Linux. The difference
might be that on Linux it is possible to open serial ports more than once,
while that doesn't work on Windows.

Best regards,
Roel


Thanks for the info. Your explanation helps a lot.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top