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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵