0

I've got a problem calling python script from php.

I've got a file:

import fnmatch, os, pythoncom, sys, win32com.client

try:
     w = win32com.client.gencache.EnsureDispatch("Word.Application")
     w.Documents.Open(r"path-to-a-file-I-want-to-convert.doc")
     doc = w.ActiveDocument # brakes here
     w.Selection.Find.ClearFormatting()
     w.ActiveDocument.SaveAs(r"save-as-name.docx", FileFormat = 12)
     w.ActiveWindow.Close()

except IOError as (errno, strerror):
     print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
     print "Could not convert data to an integer."
except:
     print "Unexpected error:", sys.exc_info()[0]
     raise

that converts .doc file into .docx format.

The script works properly until I call it from .php:

$arg = exec('C:\Python27\python.exe "path-to-script.py"', $output);
var_dump($output);

It outputs test lines if I put them there (such as print "sth") but brakes after

doc = w.ActiveDocument 

line and gives "Unexpected error". I would appreciate any suggestions on how I can call that script from .php and why it fails.

magic_turtle
  • 1,243
  • 3
  • 17
  • 37

1 Answers1

0

Can you check that the problem isn't about paths?

I could only get to work your script when providing absolute paths (for example C:/Temp/Test.doc):

import fnmatch, os, pythoncom, sys, win32com.client

try:
     w = win32com.client.gencache.EnsureDispatch("Word.Application")
     w.Documents.Open(r"C:/Temp/Test.doc")
     doc = w.ActiveDocument # brakes here
     w.Selection.Find.ClearFormatting()
     w.ActiveDocument.SaveAs(r"C:/Temp/Test.docx", FileFormat = 12)
     w.ActiveWindow.Close()

except IOError as (errno, strerror):
     print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
     print "Could not convert data to an integer."
except:
     print "Unexpected error:", sys.exc_info()[0]
     raise
adrianus
  • 3,141
  • 1
  • 22
  • 41
  • I did it using absolute paths too, so it seems like the paths are OK. I ended up converting .doc and .docx to .txt using PHP script: [link](http://stackoverflow.com/questions/19503653/how-to-extract-text-from-word-file-doc-docx-xlsx-pptx-php) – magic_turtle Jul 22 '15 at 00:25