简体   繁体   English

Pyserial:如何在打开串口之前知道它是否空闲

[英]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: 我使用Pyserial python来使用串口,​​代码如下:

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.')" . 但是,问题是,如果端口已经打开(例如另一个应用程序),当我尝试打开它时会出现错误: "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...
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 也可能更好的方法是返回串行对象或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. 因为无论错误如何,该端口都不可用...因为该函数正在测试端口的可用性,所以为什么你得到一个异常并不重要,只有你有异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM