如何用PySerial判断端口是否已打开?

15 投票
3 回答
79846 浏览
提问于 2025-04-16 18:37

我正在尝试写一个应用程序,这个程序需要在Linux电脑上使用串口,使用的是Python和PySerial。不过在这台电脑上,还有其他应用程序也在使用串口。请问我怎么才能知道某个串口在我使用之前是否已经被其他应用程序打开了呢?

3 个回答

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

检查一下Serial.serial的返回输出,它会返回一个可以被捕捉到的无效异常。

API文档
异常文档

除此之外,如果在你的程序尝试访问端口时,端口实际上是关闭的,那么抛出的错误是非致命的,并且对于失败的原因说明得相当清楚。

25

在PySerial的网站上似乎文档写得不太好,不过这个方法对我有效:

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

这个例子有点牵强,但你能明白我的意思。我知道这个问题很早就有人问过了,但我今天也遇到了同样的问题,觉得其他看到这个页面的人也会希望能找到答案。

撰写回答