Get error line number Python - python-2.7

I am trying to debug python code, I want to pin point the line number in which error occurs. As per the posts found asked here the code gives the line no of the function being called. eg
if __name__ == '__main__':
try:
foo()
except:
<the code to print line no when error occurs>
But it gives me the line no of foo(),
Please help to find the exact line no in which error occurs.
Thanks,

You have to use the third return value of sys.exc_info() they call exc_tb in your example. Instead of using exc_tb.tb_lineno, you can browse the traceback object using traceback.extract_tb(exc_tb). The repr look like :
*** extract_tb:
[('<doctest...>', 10, '<module>', 'lumberjack()'),
('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
I suppose the line you are looking for is the last line of the structure. I haven't tested but this should do :
import sys, os, traceback
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
tb = traceback.extract_tb(exc_tb)[-1]
print(exc_type, tb[2], tb[1])

Related

Getting inconsistent "invalid literal for int()" error

Although this is a super common error, I haven't found a solution for this particular issue.
I have a script with a line that reads
line = int(ser.readline())
Sometimes (not everytime!) when I run this script is get this error:
Traceback(most recent call last):
File "./project.py", line 28, in <module>
line = int(ser.readline())
ValueError: invalid literal for int() with base 10:' '
When this happens, I can simply restart the script, and it works fine.
What's going on here? Is there a way to prevent this from happening?
Here's the full script, for reference. The offending code is on line 28.
#!/usr/bin/python
import time
import serial
import subprocess
# -------------function for videos-------------
def play_vid_nonblocking(num):
return subprocess.Popen(["xterm", "-fullscreen", "-e", "omxplayer", "-o", "hdmi", "-r", "/home/pi/Ligia/{:02d}.mp4".format(num)])
# -------------sensor setup-------------
ser = serial.Serial('/dev/ttyACM0', 9600)
# -----------------------------------------
num_videos = 10
i = 1
p = None
time.sleep(60)
while True:
line = int(ser.readline())
print line
if line < 750:
if p is None or p.poll() is not None:
p = play_vid_nonblocking(i)
time.sleep(60)
i = i + 1
if i > num_videos:
i = 0
else:
pass
else:
pass
else:
pass
ser.close()
#jonrsharpe above suggested the script was sometimes reading whitespace. This was fixed by adding a "Try" statement:
try:
line = int(line)

Got "ValueError: X should be a square kernel matrix" in python

I have a short script in python and I need get the exception, but only a valueError not the full content. I explain with the code:
try:
r = str(ML_engine.Create_ML_Alg_Python(sc, m))
ML_engine.updateModel('success',r,m)
return r
except Exception as inst:
ML_engine.updateModel(str(inst), -200, m)
return str(inst)
when exception occurred, in the python console view:
File "/home/sm/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin hadoop2.6/spark-1.6.1-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/worker.py", line 106, in process
serializer.dump_stream(func(split_index, iterator), outfile)
File "/home/sm/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin-hadoop2.6/spark-1.6.1-bin-hadoop2.6/python/lib/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
vs = list(itertools.islice(iterator, batch))
File "/usr/local/lib/python2.7/dist-packages/spark_sklearn/grid_search.py", line 228, in fun
return_parameters=True, error_score=error_score)
File "/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py", line 1524, in _fit_and_score
X_train, y_train = _safe_split(estimator, X, y, train)
File "/usr/local/lib/python2.7/dist-packages/sklearn/cross_validation.py", line 1585, in _safe_split
ValueError: X should be a square kernel matrix
I need only ValueError
type(inst).__name__ will help you get the error type name. Something like this:
try:
a = float('a')
except Exception as e:
print type(e).__name__
Will print ValueError.
str(inst) or inst.message will get you the message of the error (worked always for me. But if the message isn't set, then you need to figure out another way).
I think what you are trying to say is you only need the error name. So, the aptest solution for that case would be to use sys.exc_info().
Refer: https://docs.python.org/2/library/sys.html

My first unit test, what am I doing wrong?

This is my first time trying to write a test and I'm guessing I made some obvious screw up with writing the test itself.
Here is my test:
from django.test import TestCase
from accounts.forms import UserReview
class MyTests(TestCase):
def test_forms(self):
form_data = {'headline': 'test', 'body_text': 'description of item Im selling', 'author: ben'}
form = SellForm(data=form_data)
self.assertEqual(form.is_valid(), True)
I am getting the following error:
ImportError: Failed to import test module: accounts.tests
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 254, in _find_tests
module = self._get_module_from_name(name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name
__import__(name)
File "/Users/benjamino/Desktop/myproject/myproject/accounts/tests.py", line 8
form_data = {'headline': 'test', 'body_text': 'description of item Im selling', 'author: ben'}
^
SyntaxError: invalid syntax
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Destroying test database for alias 'default'...
Why is accounts.tests failing to import? The code above is located in my accounts/tests.py.
The exception is clear on where the error is :
File "/Users/benjamino/Desktop/myproject/myproject/accounts/tests.py", line 8
form_data = {'headline': 'test', 'body_text': 'description of item Im selling', 'author: ben'}
^
SyntaxError: invalid syntax
Take a better look at the form_data: {'headline': 'test', 'body_text': 'description of item Im selling', 'author: ben'} (you have included a string instead of a name: value pair in your dict)
This is a simple syntax error, as the message tells you. Your quoting is wrong in the last element of your dict: 'author: ben' should be 'author': 'ben'
It's clear from the exception itself that the error is in your syntax. The form data format should be {name : value} but in your case it's {'string : value'} and if that doesn't solved your problem,maybe this could help you
Link

What is the error in following python code

import sys
def Hello(name):
name = name + '!!!'
print 'Hello' , name
def main():
Hello(sys.argv[1])
if __name__ == '__main__':
main()
Here is the error
Traceback (most recent call last):
File "D:\pythonPractice\firstPython.py", line 13, in <module>
main()
File "D:\pythonPractice\firstPython.py", line 9, in main
Hello(sys.argv[1])
IndexError: list index out of range
I have also tried sys.argv[2] but error remains
First things first, I think the code you originally posted (with Hello(sys.argv[0])) is not what you actually have. It doesn't match the error, which states sys.argv[1], so what you probably have is:
def main():
Hello(sys.argv[1])
As to the error then, it's because you haven't provided an argument when running. You need to do so, such that sys.argv[1] exists:
python helloprog Pax
You would find a more robust main as:
def main():
if len(sys.argv) < 2:
Hello("whoever you are")
else:
Hello(sys.argv[1])
which will detect when you haven't provided an argument, and use a suitable default rather than raising an exception.
Have you used
sys.argv[0]
Since this returns a list , you may not have elements >1

django cnotes not working

I have just installed django-cnotes
But it wont work.
It just throws up this error
Traceback (most recent call last):
File "/Library/Python/2.5/site-packages/django/core/servers/basehttp.py", line 279, in run
self.result = application(self.environ, self.start_response)
File "/Library/Python/2.5/site-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/Library/Python/2.5/site-packages/django/core/handlers/wsgi.py", line 245, in __call__
response = middleware_method(request, response)
File "/Library/Python/2.5/site-packages/django_cnote-0.3.4-py2.5.egg/cnotes/middleware.py", line 47, in process_response
signed_data = self.sign('cnotes', base64.urlsafe_b64encode(Pickle.dumps(cnotes.cnotes)))
PicklingError: Can't pickle <class 'django.utils.functional.__proxy__'>: attribute lookup django.utils.functional.__proxy__ failed
And it is not even in the normal django error debug page. What you see above is all there is on the screen.
And I have just used it as described on github, I just dont get it. Any one have an idea for what is causing this?
UPDATE:
Okay, so I have found something, I think.
message = _("You have successfully altered ")
message += edituser.username
cnotes.add(message)
message2 = _("You may now close ")
cnotes.add(message2)
This will cause the error. So I thought "Okay, I can only call it once per view" That would have been stupid and it was indeed not the cause.
The following code will produce no error
message = _("You have successfully altered ")
message += edituser.username
cnotes.add(message)
message2 = '_("You may now close ")'
cnotes.add(message2)
But is not because of the translation it uses that fine just 2 lines above, but it has to be something with doing another translation or something. Im lost.
It appears as though pickle is receiving an object of type django.utils.functional.__proxy__. This means either your input is weird, or there is a bug in cnotes.
If there is something wrong with your input to cnotes, you should see it if you take a look at the types of your messages (I used the manage.py shell):
>>> message = _("You have successfully altered ")
>>> message += "Bob Knoblick"
>>> type(message)
<type 'unicode'>
>>> message2 = _("You may now close ")
>>> type(message2)
<type 'unicode'>
>>>
If your types come back as anything other than unicode or str, I'd dig into your code and figure out where that other type is coming from, or ensure that it can be pickled.
If there is something wrong within cnotes, you should get the same error doing this:
cnotes.add(u'Foo')
cnotes.add(u'Bar')
cnotes.add(u'Baz')
Per the original author:
The translated string, _("You may now close ") was not ending up as a unicode string. One can use this to force unicode before sending to cnotes:
message2 = unicode(_("You may now close "))