Suppose you have these modules:
import module2
def a():
module1.b()
def c():
print "Hi guys!"
import module1
def b():
module1.c()
I want a function func(a())
that produces a similar output to this: (=a traceback ?)
/usr/local/lib/python2.7/dist-packages/test/module1.py
3 def a():
4 module1.b()
1 import module1
/usr/local/lib/python2.7/dist-packages/test/module2.py
3 def b():
4 module1.c()
1 import module2
/usr/local/lib/python2.7/dist-packages/test/module1.py
6 def c():
7 print "Hi guys!"
It might be possible with the standard modules traceback
and/or cgitb
and/or inspect
but I am having a hard time figuring out these modules from the documentation.
I thought it was possible doing traceback.print_stack(a())
but it just kept on loading forever for some reason. I tried other functions in those modules but without success.
@jterrace
python trapy_module.py :
import trace
def trapy(arg):
tracer = trace.Trace()
tracer.run(arg)
r = tracer.results()
r.write_results()
if __name__ == '__main__':
import random
trapy('random.random()')
Now when I do:
python trapy_module.py
I get:
--- modulename: trapy, funcname: <module>
<string>(1):
Replacing import random
with import pyglet
and random.random()
with pyglet.app.run()
just keeps running without outputting anything.
The traceback error also shows the type of error and information about that error. The above case is IndexError: list index out of range . You can fix it using the valid index number to retrieve an item from a list.
In Python, A traceback is a report containing the function calls made in your code at a specific point i.e when you get an error it is recommended that you should trace it backward(traceback). Whenever the code gets an exception, the traceback will give the information about what went wrong in the code.
traceback.print_stack works nicely for me:
>>> import traceback
>>> def what():
... traceback.print_stack()
...
>>> def hey():
... what()
...
>>> hey()
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in hey
File "<stdin>", line 2, in what
UPDATE:
You've made it clear you really don't want a traceback. You want tracing information. Here's a way you can get some trace info:
#tracetest.py
def what():
return 3
def hey():
return what()
def yo():
return hey()
import trace
tracer = trace.Trace()
tracer.run("yo()")
r = tracer.results()
r.write_results()
and running the above:
$ python tracetest.py
--- modulename: tracetest, funcname: <module>
<string>(1): --- modulename: tracetest, funcname: yo
tracetest.py(8): return hey()
--- modulename: tracetest, funcname: hey
tracetest.py(5): return what()
--- modulename: tracetest, funcname: what
tracetest.py(2): return 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With