我正在尝试使用 python 和 PySerial 编写一个在 Linux PC 中使用串行端口的应用程序。但在这台电脑上还有其他应用程序使用串口。 在尝试使用某个端口之前,如何知道该端口是否已被其他应用程序打开?
PySerial 网站上的记录似乎很糟糕,这对我有用:
ser = serial.Serial(DEVICE,BAUD,timeout=1)
if(ser.isOpen() == False):
ser.open()
这个例子有点做作,但你明白了。 我知道这个问题很久以前就被问过,但我今天也有同样的问题,并且觉得找到此页面的其他人都会很高兴找到答案。
这是我在尝试防止我的应用程序因停止并再次启动而失败时所提供的帮助。
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...