Print current call stack from a method in code
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Print Current Call Stack From A Method In Code
00:14 Accepted Answer Score 514
00:50 Answer 2 Score 156
00:56 Answer 3 Score 82
01:13 Answer 4 Score 23
01:32 Thank you
--
Full question
https://stackoverflow.com/questions/1156...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #debugging #stacktrace
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Print Current Call Stack From A Method In Code
00:14 Accepted Answer Score 514
00:50 Answer 2 Score 156
00:56 Answer 3 Score 82
01:13 Answer 4 Score 23
01:32 Thank you
--
Full question
https://stackoverflow.com/questions/1156...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #debugging #stacktrace
#avk47
ACCEPTED ANSWER
Score 514
Here's an example of getting the stack via the traceback module, and printing it:
import traceback
def f():
g()
def g():
for line in traceback.format_stack():
print(line.strip())
f()
# Prints:
# File "so-stack.py", line 10, in <module>
# f()
# File "so-stack.py", line 4, in f
# g()
# File "so-stack.py", line 7, in g
# for line in traceback.format_stack():
If you really only want to print the stack to stderr, you can use:
traceback.print_stack()
Or to print to stdout (useful if want to keep redirected output together), use:
traceback.print_stack(file=sys.stdout)
But getting it via traceback.format_stack() lets you do whatever you like with it.
ANSWER 2
Score 156
import traceback
traceback.print_stack()
ANSWER 3
Score 82
inspect.stack() returns the current stack rather than the exception traceback:
import inspect
print inspect.stack()
See https://gist.github.com/FredLoney/5454553 for a log_stack utility function.
ANSWER 4
Score 23
If you use python debugger, not only interactive probing of variables but you can get the call stack with the "where" command or "w".
So at the top of your program
import pdb
Then in the code where you want to see what is happening
pdb.set_trace()
and you get dropped into a prompt