Pyserial:如何在打开串行端口之前知道它是否可用-开发者之家 您所在的位置:网站首页 pyserial安装包 Pyserial:如何在打开串行端口之前知道它是否可用-开发者之家

Pyserial:如何在打开串行端口之前知道它是否可用-开发者之家

2023-03-28 02:54| 来源: 网络整理| 查看: 265

问题描述

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



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有