我正在使用win32Com模块将数据写入使用Python 3.5的Windows 7计算机上的Excel工作表。在它运行时我会抛出一个错误。我试过做一个"尝试/除了"阻止但我尝试的错误类型显然不是实际的错误类型。这是我的代码:
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 :(得分:3)
您需要添加导入,更具体地说是
from pywintypes import com_error
然后使用以下
except com_error as e:
答案 1 :(得分:0)
导入&#34; pywintypes&#34;我的错误尝试/除了功能正常。