How to see complete traceback? - python

I have added an assert(0) in a function to understand the sequence of function calls to this function.
Ex:
def my_func():
...lines of code...
assert(0)
...more lines of code...
The logs show only this:
Traceback (most recent call last):
File "/var/www/folder/file.py", line 273, in my_func
assert(0)
AssertionError
I want to see the complete call trace - Example: first_func -> second_func -> my_func
I tried traceback library but it is showing me the same stacktrace.
Please let me know what I am missing here.

Use traceback module for this. I.e.
>>> import traceback
>>> def my_func():
... my_other_func()
...
>>> def my_other_func():
... my_third()
...
>>> def my_third():
... print "Stack"
... traceback.print_stack()
... print "Extracted"
... print repr(traceback.extract_stack())
...
>>>
>>> my_func()
Stack
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in my_func
File "<stdin>", line 2, in my_other_func
File "<stdin>", line 3, in my_third
Extracted
[('<stdin>', 1, '<module>', None),
('<stdin>', 2, 'my_func', None),
('<stdin>', 2, 'my_other_func', None),
('<stdin>', 5, 'my_third', None)]
>>>

Related

Why Python IDE shows such error even when it is installed correctly

it show such as turtle.Terminator
AttributeError: module 'turtle' has no attribute 'forward'
>>> import turtle
>>> for i in range(50,100,10):
... for j in range(4):
... turtle.forward(i)
... turtle.left(90)
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "<string>", line 5, in forward
turtle.Terminator
Note: my excepted result is 4 square

How to obtain full stack trace after exception from function passed as parameter?

I have wrapper function, that takes other function as parameter, catches an exception and does something with it:
def exceptionCatchingWrapper(funcToCall,destForException,*args,**kwargs):
try:
r=funcToCall(*args,**kwargs)
except:
destForException["exc_info"]=sys.exc_info()
else:
return r
I realized that when an exception is caught, the stack trace taken from sys.exc_info() contains only information about exceptionCatchingWrapper() itself and nothing deeper. Is it possible and how to obtain full stack trace after such call?
import traceback
def a(x):
b(x)
def b(x):
x/0
d = {}
exceptionCatchingWrapper(a, d, 10)
Traceback is stored in the dictionary:
>>> traceback.print_tb(d['exc_info'][2]
File "<stdin>", line 3, in exceptionCatchingWrapper
File "<stdin>", line 2, in a
File "<stdin>", line 2, in b
>>> traceback.print_exception(d['exc_info'][0],d['exc_info'][1],d['exc_info'][2])
Traceback (most recent call last):
File "<stdin>", line 3, in exceptionCatchingWrapper
File "<stdin>", line 2, in a
File "<stdin>", line 2, in b
ZeroDivisionError: integer division or modulo by zero
More information in the traceback module documentation.
Not sure if this is what you need but these might be a way you can print the traceback:
import traceback
try:
s += 1 #this doesnt exist yet
except:
a = traceback.format_exc()
print a
-or-
import traceback, sys
def DummyFunc2():
s += 1 #this doesnt exist yet
def DummyFunc1():
DummyFunc2()
try:
DummyFunc1()
except:
_, err, tb = sys.exc_info()
tb_lines = traceback.extract_tb(tb)
for idx, trace in enumerate( traceback.format_list(tb_lines) ):
print "[INDEX %d]\n%s" % (idx,trace)
print err
output:
>>>
[INDEX 0]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 9, in <module>
DummyFunc1()
[INDEX 1]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 6, in DummyFunc1
DummyFunc2()
[INDEX 2]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 4, in DummyFunc2
s += 1 #this doesnt exist yet
local variable 's' referenced before assignment
>>>

Are slice objects mutable in function declaration?

After learning about how default arguments work in python, I went over all my code to look for potential bugs occuring when using mutable sequences.
Now I have a function whose signature is:
def get_measurements(self, shape = slice(None, None, None),
size = slice(None, None, None),
height = slice(None, None, None),
pressure = slice(None, None, None),
LE = slice(None, None, None),
fname = None)
And I'm wondering now, are slice objects mutable? And will this cause a problem in above case with default values?
slice objects are not mutable.
>>> s = slice(None)
>>> s
slice(None, None, None)
>>> s.start = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
>>> s.stop = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute
>>> s.step = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: readonly attribute

Case-insensitive language-to-iso code?

Is there a way to simplify the following:
>>> pycountry.languages.get(name='english')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/pycountry/db.py", line 114, in get
return self.indices[field][value]
KeyError: 'english'
>>> pycountry.languages.get(name='ENGLISH')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/pycountry/db.py", line 114, in get
return self.indices[field][value]
KeyError: 'ENGLISH'
>>> pycountry.languages.get(name='English')
<pycountry.db.Language object at 0x1096374d0>
In the above, 'English' is the only item that doesn't result in an Exception.

How can I check if an object is a file with isinstance()?

How can I check if an object is a file?
>>> f = open("locus.txt", "r")
>>> type(f)
<class '_io.TextIOWrapper'>
>>> isinstance(f, TextIOWrapper)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
isinstance(f, TextIOWrapper)
NameError: name 'TextIOWrapper' is not defined
>>> isinstance(f, _io.TextIOWrapper)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
isinstance(f, _io.TextIOWrapper)
NameError: name '_io' is not defined
>>> isinstance(f, _io)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
isinstance(f, _io)
NameError: name '_io' is not defined
>>>
I have the variable f that is a text file. When I print the type of f the Python3 interpreter shows '_io.TextIOWrapper', but if I check it with isinstance() function throws exception: NameError.
_io is the C implementation for the io module. Use io.IOBase for direct subclasses, after importing the module:
>>> import io
>>> f = open("tests.py", "r")
>>> isinstance(f, io.IOBase)
True

Categories