如何捕获pywin32com异常打开文件 [英] How to catch a pywin32com exception on opening files

查看:969
本文介绍了如何捕获pywin32com异常打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在使用COM打开一个Excel文件,并试图捕获该文件未找到错误:

I am trying to open an excel file in python using COM, and trying to catch the file not found error:

我第一次尝试捕获IOError: p>

I first tried catching the IOError:

try:
   output = xl.Workbooks.Open(Params.workbookName)
except IOError as reason:
   print reason
   exit()

但COM不引发IO错误当它有一个文件未找到问题,而是引发一个名为com_error的东西:

But COM doesn't raise an IO Error when it has a file not found problem, instead it raises something called com_error:


com_error:(-2147352567,'Exception
发生,(0,u'Microsoft Office
Excel',u'asdf.xlsx'不能
找到。检查文件的拼写
名称,并验证文件
位置是正确的。\\\
\\\
如果您是
尝试从您的列表
中打开最近使用的文件的文件,请确保
文件没有已重命名,
移动或删除。,u'C:\Program
文件(x86)\Microsoft
Office \Office12 \1033\XLMAIN11.CHM'
0,-2146827284),无)

com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Office Excel', u"'asdf.xlsx' could not be found. Check the spelling of the file name, and verify that the file location is correct.\n\nIf you are trying to open the file from your list of most recently used files, make sure that the file has not been renamed, moved, or deleted.", u'C:\Program Files (x86)\Microsoft Office\Office12\1033\XLMAIN11.CHM', 0, -2146827284), None)

所以我试过这样:

try:
   output = xl.Workbooks.Open(Params.workbookName)
except com_error as reason:
   print reason
   exit()

但是...

NameError: global name 'ComError' is not defined


推荐答案

尝试:

from pythoncom import com_error

并在中捕获区块

这篇关于如何捕获pywin32com异常打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆