2016-07-07 56 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”我的错误尝试/除了功能正常。