问题描述
|
我正在尝试使用python和PySerial编写一个使用Linux PC中的串行端口的应用程序。但是在此PC中,还有其他使用串行端口的应用程序。
在尝试使用某个端口之前,我如何知道该端口是否已被其他应用打开?
谢谢
解决方法
似乎在PySerial网站上记录不良,这对我有用:
ser = serial.Serial(DEVICE,BAUD,timeout=1)
if(ser.isOpen() == False):
ser.open()
有点人为的例子,但是您明白了。
我知道这个问题是很久以前问过的,但是今天我也遇到了同样的问题,因此觉得找到该页面的其他人都希望找到答案。
, 检查Serial.serial的返回输出,它返回可以捕获的无效异常
http://pyserial.sourceforge.net/pyserial_api.html
http://pyserial.sourceforge.net/pyserial_api.html#serial.SerialException
除此之外,如果在您的程序尝试访问端口时实际上已关闭该端口,则抛出的错误不是致命的,并且很清楚其失败的原因。
, 这是我在尝试防止应用程序由于停止并再次启动而失败时提供的帮助。
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...