How can I solve it...
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Mani\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "F:\Monu\Work\python\PROJECT\New folder\LMS.py", line 262, in onDoubalclick
cursor.execute("SELECT * FROM `TRANSECTION` WHERE Book_Id=?",(val1.get(),))
AttributeError: 'str' object has no attribute 'get'
I already convert it in string or integer but not working
def onDoubalclick(event):
test=treeview.item(treeview.selection())
print(test)
items=treeview.selection()[0]
val1=str(treeview.item(items)['values'][0])
print(type(val1))
popsearch()
DataBase()
cursor.execute("SELECT * FROM `TRANSECTION` WHERE Book_Id=?",(val1.get(),))
info=cursor.fetchall()
for ROW1 in info:
print(rows)
treeview2.insert("",END,value=ROW1)
I want to get a value that stores in val1 and search that value in the database
The error message is correct Strings do not have a get attribute.
This is the easiest way to prevent this error from crashing your program. I just removed the get() function/method call from the val1 variable.
def onDoubalclick(event):
test=treeview.item(treeview.selection())
print(test)
items=treeview.selection()[0]
val1=str(treeview.item(items)['values'][0])
print(type(val1))
popsearch()
DataBase()
cursor.execute("SELECT * FROM `TRANSECTION` WHERE Book_Id=?",(val1,))
info=cursor.fetchall()
for ROW1 in info:
print(rows)
treeview2.insert("",END,value=ROW1)
Another option is to not fix the error but surround the bug in a try/except block to prevent the program from crashing.
So as an example you could do the following:
#more code above left off to keep things simple
try:
cursor.execute("SELECT * FROM `TRANSECTION` WHERE Book_Id=?", (val1.get(),))
info=cursor.fetchall()
#the rest of your code
except Exception as e:
print "This exception was thrown: %s" % str(e)
#the rest of your code
print "Blah. Print stuff here. Print variable state. Print time."
Related
I want to make a call to a function from the finally error detection module with a variable passed. But it shows error as:
TypeError: 'NoneType' object has no attribute '__getitem__'
My code is as follows:
from mysql.connector import MySQLConnection, Error
import MySQLdb
import sys
import time
import signal
#from python_mysql_dbconfig import read_db_config
#from MySQL import row
sys.setrecursionlimit(1500)
def query_with_fetchone():
try:
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="faheemmcfc", # your password
db="python") # name of the data base
cur=db.cursor()
cursor = db.cursor()
cursor.execute("SELECT * FROM down")
queue=0
data= cursor.fetchone()
lastid=data[0]
print(data[0])
def check(lastid):
print lastid
global last
last=lastid
while True:
cursor.execute("Select * from down where id>%s"%(last))
data = cursor.fetchone()
last=data[0]
print(data[0])
print data[1]
#signal.pause()
check(lastid)
except Error as e:
print(e)
finally:
print'last',last
time.sleep(30)
check(last)
if __name__ == '__main__':
query_with_fetchone()
Here my need is to infinitely run the while loop, so whenever a new entry is made in the database it can be retrieved.
When I call the check from finally, it shows error as:
/usr/bin/python2.7 /home/faheem/PycharmProjects/untitled1/test2.py 1 1
2 CCLEANER 3 FANCONTROL 4 CCLEANER 5 FANCONTROL 6 CCLEANER last 6 6
Traceback (most recent call last): File
"/home/faheem/PycharmProjects/untitled1/test2.py", line 55, in
<module>
query_with_fetchone() File "/home/faheem/PycharmProjects/untitled1/test2.py", line 45, in
query_with_fetchone
check(last) File "/home/faheem/PycharmProjects/untitled1/test2.py", line 34, in check
last=data[0] TypeError: 'NoneType' object has no attribute '__getitem__'
Process finished with exit code 1
Please show me how to correct it or provide another method to run the while loop infinitely without allowing it to go to the finally part.
Please feel free to correct the question, as I am not so familiar with stackoverflow.
Not sure how possible this is, but here goes:
I'm trying to write an object with some slightly more subtle behavior - which may or may not be a good idea, I haven't determined that yet.
I have this method:
def __getattr__(self, attr):
try:
return self.props[attr].value
except KeyError:
pass #to hide the keyerror exception
msg = "'{}' object has no attribute '{}'"
raise AttributeError(msg.format(self.__dict__['type'], attr))
Now, when I create an instance of this like so:
t = Thing()
t.foo
I get a stacktrace containing my function:
Traceback (most recent call last):
File "attrfun.py", line 23, in <module>
t.foo
File "attrfun.py", line 15, in __getattr__
raise AttributeError(msg.format(self._type, attr))
AttributeError: 'Thing' object has no attribute 'foo'
I don't want that - I want the stack trace to read:
Traceback (most recent call last):
File "attrfun.py", line 23, in <module>
t.foo
AttributeError: 'Thing' object has no attribute 'foo'
Is this possible with a minimal amount of effort, or is there kind of a lot required? I found this answer which indicates that something looks to be possible, though perhaps involved. If there's an easier way, I'd love to hear it! Otherwise I'll just put that idea on the shelf for now.
You cannot tamper with traceback objects (and that's a good thing). You can only control how you process one that you've already got.
The only exceptions are: you can
substitute an exception with another or re-raise it with raise e (i.e make the traceback point to the re-raise statement's location)
raise an exception with an explicit traceback object
remove outer frame(s) from a traceback object by accessing its tb_next property (this reflects a traceback object's onion-like structure)
For your purpose, the way to go appears to be the 1st option: re-raise an exception from a handler one level above your function.
And, I'll say this again, this is harmful for yourself or whoever will be using your module as it deletes valuable diagnostic information. If you're dead set on making your module proprietary with whatever rationale, it's more productive for that goal to make it a C extension.
The traceback object is created during stack unwinding, not directly when you raise the exception, so you can not alter it right in your function. What you could do instead (though it's probably a bad idea) is to alter the top level exception hook so that it hides your function from the traceback.
Suppose you have this code:
class MagicGetattr:
def __getattr__(self, item):
raise AttributeError(f"{item} not found")
orig_excepthook = sys.excepthook
def excepthook(type, value, traceback):
iter_tb = traceback
while iter_tb.tb_next is not None:
if iter_tb.tb_next.tb_frame.f_code is MagicGetattr.__getattr__.__code__:
iter_tb.tb_next = None
break
iter_tb = iter_tb.tb_next
orig_excepthook(type, value, traceback)
sys.excepthook = excepthook
# The next line will raise an error
MagicGetattr().foobar
You will get the following output:
Traceback (most recent call last):
File "test.py", line 49, in <module>
MagicGetattr().foobar
AttributeError: foobar not found
Note that this ignores the __cause__ and __context__ members of the exception, which you would probably want to visit too if you were to implement this in real life.
You can get the current frame and any other level using the inspect module. For instance, here is what I use when I'd like to know where I'm in my code :
from inspect import currentframe
def get_c_frame(level = 0) :
"""
Return caller's frame
"""
return currentframe(level)
...
def locate_error(level = 0) :
"""
Return a string containing the filename, function name and line
number where this function was called.
Output is : ('file name' - 'function name' - 'line number')
"""
fi = get_c_frame(level = level + 2)
return '({} - {} - {})'.format(__file__,
fi.f_code,
fi.f_lineno)
MWE of my code distribution:
main.py
../func1.py
From main.py I call func1.py with:
data_list = [elem1, .., elemN] # Data input.
params = [1., 2., 5.] # Some parameters.
for elem in data_list:
try:
func1(elem, params) # Call function.
except Exception:
print traceback.format_exc()
This way if the function fails for some element, the main code keeps running executing the remaining elements in the list.
I want to insert a custom error message for a given block of func1, so I've defined:
try:
# try something
except ValueError:
raise ValueError('Custom error message.')
When a ValueError occurs in func1 the output I get with this, before jumping to the next element in data_list, is:
Traceback (most recent call last):
File "/main.py", line 44, in main
func1(params)
File "/func1.py", line 68, func1
raise ValueError('Custom error message.')
ValueError: Custom error message.
Why is the custom error message being printed twice?
The exception is not raised twice. There can be only one exception "up in the air".
What you are seeing is the whole traceback, an extraordinary help when it comes to finding out why and where your programme crashed, It prints line by line all the frames and ends in the line where the exception was thrown. Therefore you can read your message "again".
If you catch it and print it, you will only see the exception itself. For instance
>>> try:
... raise ValueError('Custom error message.')
... except ValueError as exc:
... print exc
...
Custom error message.
>>>
raise ValueError('Custom error message.')
ValueError: Custom error message.
"Why is the custom error message being printed twice?"
this is the last code executed in the Tracedback:
raise ValueError('Custom error message.')
This is the actual exception being echoed on your REPL:
ValueError: Custom error message.
It is not.
You are seeing the top printing because of the traceback
The first time it's printed, the interpreter is quoting the code that raised the exception, namely line 68 of func1.py.
The second time (the last line of your output), it printed the exception message.
I've recently started learning Python and started using it to create label expressions in ArcMap. I ran into an error today that I can't figure out though (and seems like it should be simple). When I try to create the following expression:
def FindLabel ( [FacilityName] ):
S = [FacilityName]
S = S.upper()
return S
I get back an error as follows:
Error 0 on line 0.
Error running expression: FindLabel(ESRIExpressionArg0)
Traceback (most recent call last):
File "<expression>", line 1, in <module>
File "<string>", line 3, in FindLabel
AttributeError: 'NoneType' object has no attribute 'upper'.
[FacilityName] is a domained field, and Null values are allowed. I understand, I think, that 'NoneType' means that [FacilityName] is being given a None value before it's trying to be returned, but I don't know how to fix the problem.
Thanks,
Ethan
I'm pretty sure all the values get returned as strings, but in the case of a null value, it might be returned as None, which would explain the error you're getting.
You can use a try..except block or make a conditional statement inside your function to ignore None values.
Here's with try..except:
def FindLabel ( [FacilityName] ):
try:
S = [FacilityName]
S = S.upper()
return S
except AttributeError:
pass
I want to save the name of the error and the traceback details into a variable. Here's is my attempt.
import sys
try:
try:
print x
except Exception, ex:
raise NameError
except Exception, er:
print "0", sys.exc_info()[0]
print "1", sys.exc_info()[1]
print "2", sys.exc_info()[2]
Output:
0 <type 'exceptions.NameError'>
1
2 <traceback object at 0xbd5fc8>
Desired Output:
0 NameError
1
2 Traceback (most recent call last):
File "exception.py", line 6, in <module>
raise NameError
P.S. I know this can be done easily using the traceback module, but I want to know usage of sys.exc_info()[2] object here.
This is how I do it:
>>> import traceback
>>> try:
... int('k')
... except:
... var = traceback.format_exc()
...
>>> print var
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'k'
You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards...
sys.exc_info() returns a tuple with three values (type, value, traceback).
Here type gets the exception type of the Exception being handled
value is the arguments that are being passed to constructor of exception class
traceback contains the stack information like where the exception occurred etc.
For Example, In the following program
try:
a = 1/0
except Exception,e:
exc_tuple = sys.exc_info()
Now If we print the tuple the values will be this.
exc_tuple[0] value will be "ZeroDivisionError"
exc_tuple[1] value will be "integer division or modulo by zero" (String passed as parameter to the exception class)
exc_tuple[2] value will be "trackback object at (some memory address)"
The above details can also be fetched by simply printing the exception in string format.
print str(e)
Use traceback.extract_stack() if you want convenient access to module and function names and line numbers.
Use ''.join(traceback.format_stack()) if you just want a string that looks like the traceback.print_stack() output.
Notice that even with ''.join() you will get a multi-line string, since the elements of format_stack() contain \n. See output below.
Remember to import traceback.
Here's the output from traceback.extract_stack(). Formatting added for readability.
>>> traceback.extract_stack()
[
('<string>', 1, '<module>', None),
('C:\\Python\\lib\\idlelib\\run.py', 126, 'main', 'ret = method(*args, **kwargs)'),
('C:\\Python\\lib\\idlelib\\run.py', 353, 'runcode', 'exec(code, self.locals)'),
('<pyshell#1>', 1, '<module>', None)
]
Here's the output from ''.join(traceback.format_stack()). Formatting added for readability.
>>> ''.join(traceback.format_stack())
' File "<string>", line 1, in <module>\n
File "C:\\Python\\lib\\idlelib\\run.py", line 126, in main\n
ret = method(*args, **kwargs)\n
File "C:\\Python\\lib\\idlelib\\run.py", line 353, in runcode\n
exec(code, self.locals)\n File "<pyshell#2>", line 1, in <module>\n'
Be careful when you take the exception object or the traceback object out of the exception handler, since this causes circular references and gc.collect() will fail to collect. This appears to be of a particular problem in the ipython/jupyter notebook environment where the traceback object doesn't get cleared at the right time and even an explicit call to gc.collect() in finally section does nothing. And that's a huge problem if you have some huge objects that don't get their memory reclaimed because of that (e.g. CUDA out of memory exceptions that w/o this solution require a complete kernel restart to recover).
In general if you want to save the traceback object, you need to clear it from references to locals(), like so:
import sys, traceback, gc
type, val, tb = None, None, None
try:
myfunc()
except:
type, val, tb = sys.exc_info()
traceback.clear_frames(tb)
# some cleanup code
gc.collect()
# and then use the tb:
if tb:
raise type(val).with_traceback(tb)
In the case of jupyter notebook, you have to do that at the very least inside the exception handler:
try:
myfunc()
except:
type, val, tb = sys.exc_info()
traceback.clear_frames(tb)
raise type(val).with_traceback(tb)
finally:
# cleanup code in here
gc.collect()
Tested with python 3.7.
p.s. the problem with ipython or jupyter notebook env is that it has %tb magic which saves the traceback and makes it available at any point later. And as a result any locals() in all frames participating in the traceback will not be freed until the notebook exits or another exception will overwrite the previously stored backtrace. This is very problematic. It should not store the traceback w/o cleaning its frames. Fix submitted here.
The object can be used as a parameter in Exception.with_traceback() function:
except Exception as e:
tb = sys.exc_info()
print(e.with_traceback(tb[2]))