基于这里的脚本:使用Python将.doc转换为.pdf,我已经得到了一个半工作的脚本,可以将.C:\Export_to_pdf中的.docx文件导出到一个新文件夹中的pdf文件。
工作代码-只需将try块替换为此内容。注意将DispatchEx语句移动到for循环外部,并将word.Quit()移到finally语句中以确保它关闭。
问题是它可以处理前几个文档,然后就会失败并显示以下错误:
(-2147352567, 'Exception occurred.', (0, u'Microsoft Word', u'Command failed', u'wdmain11.chm', 36966, -2146824090), None)
显然,这是一条不太有用的错误提示。如果我使用pdb慢慢调试它,我可以循环遍历所有文件并成功导出。如果我还在Windows任务管理器中观察进程,我可以看到WINWORD在应该开始和结束时启动,但对于较大的文件,需要更长时间才能稳定内存使用情况。这使我认为当WINWORD没有时间初始化或在客户机调度对象上调用下一个方法之前退出时,脚本会被绊倒。
是否有win32com或comtypes的方式来识别和等待进程启动或完成?
我的脚本:
import os
from win32com import client
folder = "C:\\Export_to_pdf"
file_type = 'docx'
out_folder = folder + "\\PDF"
os.chdir(folder)
if not os.path.exists(out_folder):
print 'Creating output folder...'
os.makedirs(out_folder)
print out_folder, 'created.'
else:
print out_folder, 'already exists.\n'
for files in os.listdir("."):
if files.endswith(".docx"):
print files
print '\n\n'
try:
for files in os.listdir("."):
if files.endswith(".docx"):
out_name = files.replace(file_type, r"pdf")
in_file = os.path.abspath(folder + "\\" + files)
out_file = os.path.abspath(out_folder + "\\" + out_name)
word = client.Dispatch("Word.Application")
doc = word.Documents.Open(in_file)
print 'Exporting', out_file
doc.SaveAs(out_file, FileFormat=17)
doc.Close()
word.Quit()
except Exception, e:
print e
工作代码-只需将try块替换为此内容。注意将DispatchEx语句移动到for循环外部,并将word.Quit()移到finally语句中以确保它关闭。
try:
word = client.DispatchEx("Word.Application")
for files in os.listdir("."):
if files.endswith(".docx") or files.endswith('doc'):
out_name = files.replace(file_type, r"pdf")
in_file = os.path.abspath(folder + "\\" + files)
out_file = os.path.abspath(out_folder + "\\" + out_name)
doc = word.Documents.Open(in_file)
print 'Exporting', out_file
doc.SaveAs(out_file, FileFormat=17)
doc.Close()
except Exception, e:
print e
finally:
word.Quit()
FileFormat
规范在哪里? - Lei Yang