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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With