title: How can I fix "[Error 6] The handle is invalid." with PySerial
body: <p>I'm trying to connect to my phone from my Windows 7 PC using PySerial with the following code:</p>
  
  <pre><code>import wmi
  import serial
  
  c = wmi.WMI()
  modem = c.query("SELECT * FROM Win32_POTSModem").pop()
  ser = serial.Serial(modem.AttachedTo, modem.MaxBaudRateToSerialPort)
  
  try:
      ser.write('at \r\n')
      print ser.readline()
  finally:
      ser.close()
  </code></pre>
  
  <p>But get the following error on the write call:</p>
  
  <pre><code>Traceback (most recent call last):
    File "D:\Alasdair\Documents\Python Scripts\Phone Interface\test.py", line 14, in &lt;module&gt;
      ser.write('at \r\n')
    File "C:\Python26\Lib\site-packages\serial\serialwin32.py", line 255, in write
      raise SerialException("WriteFile failed (%s)" % ctypes.WinError())
  SerialException: WriteFile failed ([Error 6] The handle is invalid.)
  </code></pre>
  
  <p>I've tried connecting with TeraTerm and that works fine, so it's not a problem with the connection to the phone itself.</p>
  
  <p>I've been searching around for ages trying to find a solution but haven't come up with anything that works. Any ideas?</p>