python: how to get up until the last error made by my code

Clash Royale CLAN TAG#URR8PPP
python: how to get up until the last error made by my code
So when I run this... the error is on this line bomb=pd.DataFrame(here,0) but the trace shows me a bunch of code from the pandas library to get to the error.
bomb=pd.DataFrame(here,0)
pandas
import traceback,sys
import pandas as pd
def error_handle(err_var,instance_name=None): #err_var list of variables, instance_name
print(traceback.format_exc())
a= sys._getframe(1).f_locals
for i in err_var: # selected var for instance
t= a[instance_name]
print i,"--->",getattr(t,i.split(".")[1])
here=['foo']
err_var = ['self.needthisone','self.constant2']
class test:
def __init__(self):
self.constant1 = 'hi1'
#self.constant2 = 'hi2'
#self.needthisone = ':)'
for i in err_var:
setattr(self, i.split('.')[1], None)
def other_function(self):
self.other_var=5
def testing(self):
self.other_function()
vars=[self.constant1,self.constant2]
try:
for i in vars:
bomb=pd.DataFrame(here,0)
except:
error_handle(err_var,'self')
t=test()
t.testing()
How do I suppress all that and have the error just look like this:
Traceback (most recent call last):
File "C:UsersJasonGoogle Drivepythonerror_handling.py", line 34, in testing
bomb=pd.DataFrame(here,0)
TypeError: Index(...) must be called with a collection of some kind, 0 was passed
I just want what's relevant to me and the last line of code that I wrote which was bad.
This is the original:
Traceback (most recent call last):
File "C:UsersJasonGoogle Drivepythonerror_handling.py", line 35, in testing
bomb=pd.DataFrame(here,0)
File "C:Python27libsite-packagespandascoreframe.py", line 330, in __init__
copy=copy)
File "C:Python27libsite-packagespandascoreframe.py", line 474, in _init_ndarray
index, columns = _get_axes(*values.shape)
File "C:Python27libsite-packagespandascoreframe.py", line 436, in _get_axes
index = _ensure_index(index)
File "C:Python27libsite-packagespandascoreindexesbase.py", line 3978, in _ensure_index
return Index(index_like)
File "C:Python27libsite-packagespandascoreindexesbase.py", line 326, in __new__
cls._scalar_data_error(data)
File "C:Python27libsite-packagespandascoreindexesbase.py", line 678, in _scalar_data_error
repr(data)))
TypeError: Index(...) must be called with a collection of some kind, 0 was passed
self.needthisone ---> None
self.constant2 ---> None
I'm just using notepad++ and running
C:Python27Libidlelibidle.bat -r "$(FULL_CURRENT_PATH)" with a shortcut– jason
Aug 1 at 16:07
C:Python27Libidlelibidle.bat -r "$(FULL_CURRENT_PATH)"
And the entire first block of code is being output by your interpreter??
– GetHacked
Aug 1 at 16:08
I have not used an IDE up til this point. Easier just use an IDE to get all of these features?
– jason
Aug 1 at 16:13
what would you want to be displayed when you call into your own code before calling pandas? In that case the full stack trace would have two lines of your code before the lines from pandas. Do you just want lines from pandas to be suppressed?
– lxop
Aug 1 at 16:16
3 Answers
3
I would highly encourage you not to limit your traceback output, because it is bad practice. You feel like there is too much info; but this is only because you already looked at it already and you know what error to look for.
In most cases, the problem may be hiding elsewhere. So there has to be a better way to achieve what you look for.
Why not wrap your function call in a try except clause and print the exception message? Take this scenario for example:
try except
def f():
a = 0
i = 1
print i/a
def another_func():
print 'this is another func'
return f()
def higher_level_func():
print 'this is higher level'
return another_func()
if __name__ == '__main__':
try:
higher_level_func()
except Exception as e:
print 'caught the exception: -'.format(type(e)__name__, e.message)
When called, this is the output:
this is higher level
this is another func
caught the exception: ZeroDivisionError-integer division or modulo by zero
This prints only the relevant exception in your code, hiding any information about the traceback, but the traceback is still available and you can print it as well (just raise the exception from your except block).
Compared to this, if I remove the try except block:
try except
this is higher level
this is another func
caught the exception: integer division or modulo by zero
Traceback (most recent call last):
File "test.py", line 17, in <module>
higher_level_func()
File "test.py", line 12, in higher_level_func
return another_func()
File "test.py", line 8, in another_func
return f()
File "test.py", line 4, in f
print i/a
ZeroDivisionError: integer division or modulo by zero
You better use this technique to capture the relevant exception, rather than limiting the tracebacks. If you want your program to stop, just add sys.exit(1) in the except block.
sys.exit(1)
except
You can define how far back a traceback goes using the sys.traceback variable. If your code is only 3 levels deep, (a function in a class in a file), then you can define this appropriately with the code:
sys.traceback
sys.tracebacklimit = 3
at the top of your file. BE CAREFUL WITH THIS: As you write more code, the portion that you've written will become deeper and deeper, and you may sometime soon find that an error is a result of something deeper in the traceback. As a general rule, I would avoid using the variable and just deal with a longer traceback for the time being.
Please, don't ever think about limiting the stack trace. It is very important.
Only at this moment, in this small example of yours, the error really is in your code.
But in an infinite other cases, an error could be triggered much deeper than that. It could be in the framework, or even out of the code whatsoever, like a configuration error, or it could be in the platform, like an Out of Memory error, etc.
The stack trace is there to help you. It lists all frames the compiler was executing, to give you all the info you need to understand what was going on.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Are you just using the default Python interpreter or some kind of IDE?
– GetHacked
Aug 1 at 16:05