如何使用 PySerial 知道端口是否已打开?

问题描述 投票:0回答:3

我正在尝试使用 python 和 PySerial 编写一个在 Linux PC 中使用串行端口的应用程序。但在这台电脑上还有其他应用程序使用串口。 在尝试使用某个端口之前,如何知道该端口是否已被其他应用程序打开?

python pyserial
3个回答
25
投票

PySerial 网站上的记录似乎很糟糕,这对我有用:

ser = serial.Serial(DEVICE,BAUD,timeout=1)
if(ser.isOpen() == False):
    ser.open()

这个例子有点做作,但你明白了。 我知道这个问题很久以前就被问过,但我今天也有同样的问题,并且觉得找到此页面的其他人都会很高兴找到答案。


3
投票

这是我在尝试防止我的应用程序因停止并再次启动而失败时所提供的帮助。

import serial

try:
  ser = serial.Serial( # set parameters, in fact use your own :-)
    port="COM4",
    baudrate=9600,
    bytesize=serial.SEVENBITS,
    parity=serial.PARITY_EVEN,
    stopbits=serial.STOPBITS_ONE
  )
  ser.isOpen() # try to open port, if possible print message and proceed with 'while True:'
  print ("port is opened!")

except IOError: # if port is already opened, close it and open it again and print message
  ser.close()
  ser.open()
  print ("port was already open, was closed and opened again!")

while True: # do something...

2
投票

检查Serial.serial的返回输出,它返回一个可以捕获的无效异常。

API文档
异常文档

除此之外,如果当您的程序尝试访问该端口时该端口实际上已关闭,则抛出的错误是非致命的,并且非常清楚其失败的原因。

© www.soinside.com 2019 - 2024. All rights reserved.