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 想请教大家关于机器学习的问题
  • ¥15 虚幻UE保存Actor位置失败
  • ¥15 多个.nii合并为.nii.gz格式
  • ¥50 现在需要统计2023年全年 “签收时间(qssj)” 到 “提交时间(tjsj)” 小于半小时的业务量,但是要排除掉周末的时间,同时还要排除中午休息的时间。
  • ¥50 opencv模板匹配为何图像差别大仍然匹配数值高?
  • ¥15 如何成功完成主菜单和分菜单的代码编程C++
  • ¥15 怎样采集或者其它途径拿到全国最新个体工商户数据
  • ¥20 我是一名大学生,想学习java是自学还是报培训班呢
  • ¥15 pycharm该如何爬取网易云歌曲下的评论?
  • ¥15 java调用sap webservice问题