title: python doc to docx conversion, comtypes.Documents.Open throwing ValueError: NULL COM pointer access
body: <h2><strong>Background</strong></h2>
  
  <p>I have an application, wherein I am suppose to convert .doc to .docx. After which .docx files are processed for data mining. This service is accessed by the end-user using a web interface. The web application is developed in Django 1.6.</p>
  
  <p>To convert .doc to .docx, we require Windows platform with MS Office installed. Having said that, I have a AWS Windows Server 2012 R2 instance(it's Windows 64bit) running. I am using Apache(64bit) with mod_wsgi and Python 2.7.8(64bit).</p>
  
  <hr>
  
  <p>Now, here is my code to convert .doc to .docx </p>
  
  <pre><code>import tempfile, sys
  import comtypes, comtypes.client
  
  def convert(source):
      tmpfile = tempfile.NamedTemporaryFile(delete=False)
      tmpname = tmpfile.name + ".docx"
      tmpfile.close()
      os.unlink(tmpfile.name)
  
      try:
          comtypes.CoInitialize();
          wordapp = comtypes.client.CreateObject('Word.Application')
          doc = wordapp.Documents.Open(source, ReadOnly=True)
          doc.SaveAs(tmpname, FileFormat=16)
          doc.Close()
          wordapp.Quit()
      except:
          print sys.exc_info()
  
      if os.path.exists(tmpname):
          return tmpname
      else:
          return None
  </code></pre>
  
  <p>The error that I am getting is </p>
  
  <pre><code>(&lt;type 'exceptions.ValueError'&gt;, ValueError('NULL COM pointer access',), &lt;traceback object at 0x00000085CE65AC08&gt;)
  </code></pre>
  
  <p>on line</p>
  
  <pre><code>doc = wordapp.Documents.Open(source, ReadOnly=True)
  </code></pre>
  
  <p>But the interesting thing that's happening is, this error only occurs when I use the web interface. That is if I go through Apache and call this code.</p>
  
  <p>I have tried to run this code directly from command line as a script, it works just fine.</p>
  
  <p>When conversion happens as a part of Django view, I am getting this error.</p>
  
  <p>Thanks in advance.</p>
  
  <p>Regards,</p>
  
  <p>Prathamesh</p>