14

I'm trying to write an App that uses serial ports in a Linux PC, using python and PySerial. But in this PC there are other Apps using serial ports. How can I know if a port is already open by other App before trying to use it?

thanks

nicolango
  • 141
  • 1
  • 1
  • 4

3 Answers3

25

Seems to be badly documented on the PySerial website, this works for me:

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

A bit of a contrived example, but you get the idea. I know this question was asked a long time ago, but I had the same question today and felt anyone else finding this page would appreciate finding an answer.

StampyCode
  • 7,218
  • 3
  • 28
  • 44
  • Just realised the question was asking something slightly different from this, but I hope this answer will still be helpful! – StampyCode May 27 '13 at 09:20
  • 2
    I just found this one - top of the list in Google, in August 2017. Thank you for posting this the way you did. It answered my question exactly. In my case it means the program is already running. I use ssh into the computers and sometimes I have the data-logger program `ssx`running from the console. Python can now use this to detect it without just aborting, and use `os.system("killall ssx")` to stop the other one all by itself. This only happens when I am making changes, but it was enough for me to search. And here you are. TNX. – SDsolar Aug 24 '17 at 01:19
3

This is what me helped 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...
Tobias
  • 31
  • 1
1

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

API documentation
Exceptions documentation

Other than that, if the port is in fact closed when your program attempts to access it, the error thrown is non-fatal and is fairly clear about the reason it failed.

greybeard
  • 2,249
  • 8
  • 30
  • 66
Fuller
  • 53
  • 1
  • 3
  • 13
  • 1
    The sourceforge links are dead, Jim. Long live permalinks (or answer the question directly instead of by reference to another page). – ndemarco Sep 23 '22 at 20:13