2011-06-13 58 views
0

我试图使用COM打开了一个Python Excel文件,并试图赶上找不到文件的错误:如何捕捉pywin32com例外,上打开文件

我第一次尝试捕捉IO错误:

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

但COM不引发IO错误时,有一个文件没有发现问题,而不是它提出了一种叫做com_error:

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)

所以逻辑上我尝试这样做:

​​

但是......

NameError: global name 'ComError' is not defined 

回答

1

尝试:

from pythoncom import com_error 

,并抓住它在你的except