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

有些话、适合烂在心里 提交于 2019-12-23 10:19:15

问题


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...

回答1:


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.



来源:https://stackoverflow.com/questions/24493379/pyserial-how-to-know-if-a-serial-port-is-free-before-open-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!