As @VooDooNOFX said, there's no technical limitation on preventing the other processes from opening the same port (device). However, on Linux you can lock the file to prevent your application from using the same port multiple times.
import fcntl, serial
s = serial.Serial(0)
fcntl.flock(s.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
In this case, your application will try to obtain an exclusive lock (LOCK_EX
) on the serial port. Thanks to LOCK_NB
, the call will fail immediately if any other process has locked the serial port already — through raising IOError
(or BlockingIOError
sub-exception in Python 3.3).
This has two advantages over the other solution:
- You are not introducing any non-standard files but use system-provided method which brings better interoperability,
- The lock is immediately released when your process exits, so you don't have to worry about stale locks.
So, your function would look like:
def available_ttys():
for tty in serial.tools.list_ports.comports():
try:
port = serial.Serial(port=tty[0])
if port.isOpen():
try:
fcntl.flock(port.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'Port {0} is busy'.format(tty)
else:
yield port
except serial.SerialException as ex:
print 'Port {0} is unavailable: {1}'.format(tty, ex)