I am using the win32Com module to write data to an excel sheet on a Windows 7 machine with Python 3.5. While it is running I get thrown an error. I tried making a "try/except" block but the error type I attempted is apparently not an actual error type. Here is my code :
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
The traceback I get is this :
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)
During handling of the above exception, another exception occurred:
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
I am used to seeing things like here ( https://docs.python.org/2/library/exceptions.html#exception-hierarchy ) and have been basing my method of writing the try/except off of here ( https://docs.python.org/3/tutorial/errors.html )
My question is how do I determine the error type that I am trying to catch based on the top portion of the traceback?
You need to add an import, more specifically
from pywintypes import com_error
then use the following
except com_error as e:
By importing "pywintypes" my error try/except functions properly.
Related
I want to print an error's line number and error message in a nicely displayed way. The follow is my code, which uses linecache:
import linecache
def func():
if xx == 1:
print('ok')
try:
func()
except:
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print_('ERROR - (LINE {} "{}"): {}'.format(lineno, line.strip(), exc_obj))
However, this only gives where the func() is called:
ERROR - (LINE 8 ""): name 'xx' is not defined
Is there a way to print the line number where the error actually occured, which should be Line 4? Or even better, can I print Line 8 and then trace back to line 4? For example, if I do not use try - except, the code:
def func():
if xx == 1:
print('ok')
func()
will give me the following error message, which is much better to locate the error:
File "<input>", line 5, in <module>
File "<input>", line 2, in func
NameError: name 'xx' is not defined. Did you mean: 'xxx'?
You can use traceback and sys modules to get advanced traceback output like you are wishing for.
Here is an example:
import traceback
import sys
def func():
zeroDivide = 1 / 0
try:
func()
except Exception:
print(traceback.format_exc()) # This line is for getting traceback.
print(sys.exc_info()[2]) # This line is getting for the error type.
Output will be:
Traceback (most recent call last):
File "b:\abc\1234\pppp\main.py", line 10, in <module>
func()
File "b:\abc\1234\pppp\main.py", line 7, in func
zeroDivide = 1 / 0
ZeroDivisionError: division by zero
You can use the traceback module to get the line number of the error,
import traceback
def function():
try:
# code
except:
tb_list = traceback.extract_tb(sys.exc_info()[2])
line_number = tb_list[-1][1]
print("An error occurred on line:", line_number)
You can use the traceback.extract_tb() function. This function returns a list of traceback objects, each of which contain information about the stack trace. The last element of this list, tb_list[-1], holds information about the line where the exception occurred. To access the line number, you can use the second element of this tuple, tb_list[-1][1]. This value can then be printed using the print() function.
To get the line number as an int you can get the traceback as a list from traceback.extract_tb(). Looking at the last item gives you the line where the exception was raised:
#soPrintLineOfError2
import sys
import traceback
def func():
if xx == 1:
print('ok')
try:
func()
except Exception as e:
tb = sys.exc_info()[2]
ss = traceback.extract_tb(tb)
ss1 = ss[-1]
print(ss1.line)
print(ss1.lineno)
Output:
if xx == 1:
6
hi all i have this problem when i try to export object through WBlock what is wrong there i'm try to do simple python work (note: i'm beginners :D) .. any help
from pyautocad import Autocad, APoint,utils
import win32com.client
AutoCAD = win32com.client.dynamic.Dispatch("AutoCAD.Application")
acad = Autocad(create_if_not_exists = False)
acad.Visible=True
doc = AutoCAD.ActiveDocument
layersList = doc.Layers
for l in layersList:
object = acad.iter_objects()
if l.name == "0":
pass
else:
for o in object:
if o.ObjectName == "AcDbText":
SelectionSet = doc.SelectionSets.Item(o.ObjectName).Name
directoryN = "C:\\Temp\\{}_{}.dwg".format(l.name,o.TextString)
doc.WBlock(directoryN,SelectionSet)
here what i Get
AcDbText
Traceback (most recent call last):
File "C:/Temp/Exporter.py", line 23, in <module>
doc.WBlock(directoryN,SelectionSet)
File "<COMObject <unknown>>", line 2, in WBlock
pywintypes.com_error: (-2147352571, 'Type mismatch.', None, 2)
thanks
i'm try to export every text as WBlock
I don't success to fix this error on my code. Python wrote me this error message:
"Traceback (most recent call last):
File "C:\Users\ChloƩ CHAUMETON\Documents\BioAxial\1_R&D\4_Software\2_Python\Measurement_script\Matlab_to_Python\2019\Chloe_script_V3.py", line 114, in <module>
if 0 < len((lrir)(lrir.name_file)):
AttributeError: 'function' object has no attribute 'name_file' "
I defined the "name_file = 'BSR_Main.exe2018_09_14.csv' " up of my code but I don't understand why python don't attribute this name fto the function. Here is my code.
i_r=[]
def lrir():
lrir = liste_record[i_r]
name_file = 'BSR_Main.exe2018_09_14.csv';
for i_r in range(0,rec-1):
if 0 < len((lrir)(lrir.name_file)):
str1 = ligne.find(lrir.name_file,'/')
pr_rep = os.path.join(dir_PR,s(i_r).name_file)
log_rep = os.path.join(pr_rep,'Log')
log_file = glob.glob(os.path.join(log_rep,'*.log'))
print('log file:',log_file)
Anyone come across this before?
import boto
conn = boto.dynamodb.connect_to_region('eu-west-1', aws_access_key_id=aws_key, aws_secret_access_key=aws_secret)
table = conn.get_table('TweetSample')
print table.scan(limit=1)
error:
Traceback (most recent call last):
File "test.py", line 9, in <module>
print table.scan(limit=1)
File "table.py", line 518, in scan
return self.layer2.scan(self, *args, **kw)
TypeError: scan() got an unexpected keyword argument 'limit'
[Finished in 0.4s with exit code 1]
I don't even know...
According to the documentation, scan method of boto.dynamodb.table.Table (which is returned by boto.dynamodb.layer2.Layer2.get_table) does not accepts limit, but max_results.
And the result is a generator. So, if you want to print it you should iterate it:
import boto.dynamodb
conn = boto.dynamodb.connect_to_region(
'eu-west-1',
aws_access_key_id=aws_key,
aws_secret_access_key=aws_secret)
table = conn.get_table('TweetSample')
for row in table.scan(max_results=1):
print row
or convert it to a sequence:
print list(table.scan(max_results=1))
I've tried two different versions of the same function:
def position_of(self, table_name, column_name):
positions = self.heading_positions()
position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
return position
-
def position_of(self, table_name, column_name):
positions = self.heading_positions()
try:
position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
except KeyError:
raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
return position
With the first version, I get the following error, which is fine:
Traceback (most recent call last):
File "./import.py", line 15, in <module>
g.process()
File "/home/jason/projects/mcifdjango/mcif/models/generic_import.py", line 39, in process
row.process()
File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 18, in process
self.save()
File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 26, in save
self.output("Phone: " + self.value('customer', 'phone'));
File "/home/jason/projects/mcifdjango/mcif/models/csv_row.py", line 60, in value
print self.generic_import.import_profile.position_of(table_name, column_name)
File "/home/jason/projects/mcifdjango/mcif/models/import_profile.py", line 22, in position_of
position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
KeyError: 'customer.phone'
But the second version - the one that has the more informative error description - fails silently. Why is this?
The second version of position_of works fine for me. I have turned it into a minimal complete program as follows:
class Test(object):
def heading_positions(self):
return {}
def position_of(self, table_name, column_name):
positions = self.heading_positions()
try:
position = positions['{t}.{c}'.format(t=table_name, c=column_name)]
except KeyError:
raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
return position
a = Test()
a.position_of('customer', 'phone')
When I run this (using Python 2.6.6 on MacOS X) I get the following error message as expected:
Traceback (most recent call last):
File "./a.py", line 17, in <module>
a.position_of('customer', 'phone')
File "./a.py", line 13, in position_of
raise RuntimeError('No heading found for {t}.{c} in import profile "{ip}"'.format(t=table_name, c=column_name, ip=self))
RuntimeError: No heading found for customer.phone in import profile "<__main__.Test object at 0x100426ad0>"
This shows that catching the KeyError and turning it into a RuntimeError works fine. Does this example work for you? As Sven already writes, a possible explanation would be if you catch RuntimeError but not KeyError somewhere in the call chain.