Python PySerial. How do I know if a port is open?

I am trying to write an application that uses serial ports on a Linux PC using python and PySerial. But there are other applications on this PC that use serial ports. How can I find out if a port is open by another application before trying to use it?

thank

+7
pyserial
May 30 '11 at 16:34
source share
3 answers

This seems to be poorly documented on the PySerial website, this works for me:

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

A little far-fetched example, but you get the idea. I know this question was asked a long time ago, but today I had the same question, and I felt that someone else would find this page, it would be useful to find the answer.

+14
May 27 '13 at 9:17
source share

Check the output of Serial.serial, it returns an invalid exception that can be caught

http://pyserial.sourceforge.net/pyserial_api.html http://pyserial.sourceforge.net/pyserial_api.html#serial.SerialException

In addition, if the port is actually closed when your program tries to access it, the error caused by the error is not fatal and is understandable enough because of its failure.

+1
Jul 23 2018-11-23T00:
source share

This is what helped me when trying to prevent my application from failing because it was stopped and started again.

 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... 
0
Nov 21 '16 at 16:15
source share



All Articles