2016-07-07 40 views
2

我正在使用win32Com模塊將數據寫入使用Python 3.5的Windows 7計算機上的Excel工作表。當它運行時,我得到一個錯誤。我嘗試了一個「try/except」塊,但我嘗試的錯誤類型顯然不是實際的錯誤類型。這裏是我的代碼:確定錯誤/異常類型Python

import win32com.client as win32 
import sqlite3 

def writeWords(storage): 
excel = win32.gencache.EnsureDispatch('Excel.Application') 
excel.Visible = True 
wb = excel.Workbooks.Add() 
ws = wb.Worksheets('Sheet1') 
i = 0 
storLen = len(storage) 
while i < storLen: 
    varX = storage[i] 
    lenVar = len(varX) 
    q = 0 
    while q < lenVar: 
     tarf = str(storage[i][q].encode('ascii', errors='ignore')).lstrip("b\'").rstrip("\'") 
     try : 
      ws.Cells(q+1,i+1).Value = (tarf) 
     except pywintypes.com_error: 
      print("Error") 
      q +=1 
     q += 1 
    i += 1 

回溯我得到的是這樣的:

Traceback (most recent call last): 
    File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 65, in writeWords 
    ws.Cells(q+1,i+1).Value = (tarf) 
    File "C:\Users\LewTo002\AppData\Local\Programs\Python\Python35\lib\site-packages\win32com\client\__init__.py", line 474, in __setattr__ 
    self._oleobj_.Invoke(*(args + (value,) + defArgs)) 
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146777998), None) 

在處理上述異常,另一個異常:

Traceback (most recent call last): 
    File "C:\Users\LewTo002\AppData\Local\Programs\Python\Python35\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript 
    exec(codeObject, __main__.__dict__) 
    File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 100, in <module> 
    writeWords(storage) 
    File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 66, in writeWords 
    except pywintypes.com_error: 
NameError: name 'pywintypes' is not defined 

我習慣看到的東西像這裏(https://docs.python.org/2/library/exceptions.html#exception-hierarchy),並一直基於我的寫作方法/這裏除外(https://docs.python.org/3/tutorial/errors.html

我的問題是我如何根據追蹤的頂部來確定我試圖捕獲的錯誤類型?

+0

你能證明你的進口嗎? –

+2

聽起來像你沒有導入'pywintypes'。 – user2357112

+0

我已將我的導入添加到主帖子中。你是正確的,我沒有導入pywintypes。我會導入並重試,看看會發生什麼。感謝user235! –

回答

3

您需要添加一個導入,更具體

from pywintypes import com_error 

然後使用以下

except com_error as e: 
+0

,謝謝你更清楚的答案。我不確定你的建議中「as e:」是什麼,它的目的是什麼?非常感謝你提供的信息! –

+0

@ToddLewden將錯誤對象分配給名稱「e」。這對解析錯誤消息很有幫助。 –

+0

@DavidZemmens說的。如果您想從Error對象中提取信息,則將其分配給一個變量。這也是常見的做法。 –

0

通過導入「pywintypes」我的錯誤嘗試/除了功能正常。