Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PySerial.How to know if a port is already open?

Tags:

pyserial

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

like image 934
nicolango Avatar asked May 30 '11 16:05

nicolango


People also ask

Is PySerial the same as serial?

PySerial is a library which provides support for serial connections ("RS-232") over a variety of different devices: old-style serial ports, Bluetooth dongles, infra-red ports, and so on.

How do I close a COM port in Python?

If you the port is open and you call serial. Serial("com4", 9600) it will attempt to re-open the port again and fail. If serial_port was assigned successfully then serial_port. close() should close it.


2 Answers

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.

like image 179
StampyCode Avatar answered Oct 11 '22 20:10

StampyCode


Check the return 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

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.

like image 25
Fuller Avatar answered Oct 11 '22 20:10

Fuller