Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyserial: How to know if a serial port is free before open it

I use python with Pyserial to use the serial port, the code like this:

import serial
portName = 'COM5'

ser = serial.Serial(port=portName)

# Use the serial port...

But, the problem is, if the port is already open (by another application for example), I get an error when I try to open it like: "SerialException: could not open port 'COM5': WindowsError(5, 'Access is denied.')".

And I would like to know if I can open the port before trying to open it to avoid this error. I would like to use a kind of condition and open it only if I can:

import serial
portName = 'COM5'

if portIsUsable(portName):
    ser = serial.Serial(port=portName)

# Use the serial port...

EDIT:

I have found a way to do it:

import serial
from serial import SerialException

portName = 'COM5'

try:
    ser = serial.Serial(port=portName)
except SerialException:
    print 'port already open'

# Use the serial port...
like image 864
Alain Avatar asked Jun 30 '14 15:06

Alain


1 Answers

def portIsUsable(portName):
    try:
       ser = serial.Serial(port=portName)
       return True
    except:
       return False

as mentioned in the comments watch out for race conditions under circumstances where you are opening and closing alot ...

also it might be better to just return the serial object or None

def getSerialOrNone(port):
    try:
       return serial.Serial(port)
    except:
       return None

[edit] I intentionally left the except as a catch-all, because I posit that the actual failure does not matter. as regardless of the error, that port is not usable ... since the function is testing the usability of a port, it does not matter why you get an exception it only matters that you got an exception.

like image 131
Joran Beasley Avatar answered Nov 14 '22 23:11

Joran Beasley