douquan2023 2015-07-16 06:55
浏览 180
已采纳

问题从php调用python脚本(Python脚本自己工作)

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.

  • 写回答

1条回答 默认 最新

  • dongxian1699 2015-07-16 08:09
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。