2011-06-13 59 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