如何用PySerial判断端口是否已打开?
我正在尝试写一个应用程序,这个程序需要在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...
25
在PySerial的网站上似乎文档写得不太好,不过这个方法对我有效:
ser = serial.Serial(DEVICE,BAUD,timeout=1)
if(ser.isOpen() == False):
ser.open()
这个例子有点牵强,但你能明白我的意思。我知道这个问题很早就有人问过了,但我今天也遇到了同样的问题,觉得其他看到这个页面的人也会希望能找到答案。