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

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏