title: Pyserial: How to know if a serial port is free before open it
body: <p>I use python with <code>Pyserial</code> to use the serial port, the code like this:  </p>
  
  <pre><code>import serial
  portName = 'COM5'
  
  ser = serial.Serial(port=portName)
  
  # Use the serial port...
  </code></pre>
  
  <p>But, the problem is, if the port is already open (by another application for example), I get an error when I try to open it like: <code>"SerialException: could not open port 'COM5': WindowsError(5, 'Access is denied.')"</code>.  </p>
  
  <p>And I would like to know if I can open the port before trying to open it to avoid this error. I would like to use a kind of condition and open it only if I can:  </p>
  
  <pre><code>import serial
  portName = 'COM5'
  
  if portIsUsable(portName):
      ser = serial.Serial(port=portName)
  
  # Use the serial port...
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I have found a way to do it:</p>
  
  <pre><code>import serial
  from serial import SerialException
  
  portName = 'COM5'
  
  try:
      ser = serial.Serial(port=portName)
  except SerialException:
      print 'port already open'
  
  # Use the serial port...
  </code></pre>