Pyserial:如何在打开串行端口之前知道它是否可用 [英] Pyserial: How to know if a serial port is free before open it

查看:40
本文介绍了Pyserial:如何在打开串行端口之前知道它是否可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用python和Pyserial来使用串口,​​代码如下:

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

但是,问题是,如果端口已经打开(例如被另一个应用程序打开),当我尝试打开它时会出现错误,例如:"SerialException: could not open port 'COM5': WindowsError(5, '访问被拒绝.')".

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

我找到了一种方法:

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

也最好只返回串行对象或 None

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] 我有意将 except 作为一个包罗万象的内容,因为我认为实际的失败并不重要.无论错误如何,该端口都不可用......因为该函数正在测试端口的可用性,所以您为什么会遇到异常并不重要,重要的是您遇到了异常.

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

这篇关于Pyserial:如何在打开串行端口之前知道它是否可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆