Print current call stack from a method in code
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.
How to print java method call stack?
Here is how you print the stack trace from a given location in your source file.
System.out.println("Printing stack trace:");
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (int i = 1; i < elements.length; i++) {
StackTraceElement s = elements[i];
System.out.println("\tat " + s.getClassName() + "." + s.getMethodName() + "(" + s.getFileName() + ":" + s.getLineNumber() + ")");
}
print call stack in C or C++
For a linux-only solution you can use backtrace(3) that simply returns an array of void *
(in fact each of these point to the return address from the corresponding stack frame). To translate these to something of use, there's backtrace_symbols(3).
Pay attention to the notes section in backtrace(3):
The symbol names may be unavailable
without the use of special linker
options.
For systems using the GNU linker, it is necessary to use the
-rdynamic linker
option. Note that names of "static" functions are not exposed,
and won't be
available in the backtrace.
How can I get the current stack trace in Java?
You can use Thread.currentThread().getStackTrace()
.
That returns an array of StackTraceElement
s that represent the current stack trace of a program.
How to print call stack with argument values?
I wrote a module that does something like this a while ago.
My notes say it works in both Python 2 and 3.
from __future__ import print_function
from itertools import chain
import traceback
import sys
def stackdump(id='', msg='HERE'):
print('ENTERING STACK_DUMP' + (': '+id) if id else '')
raw_tb = traceback.extract_stack()
entries = traceback.format_list(raw_tb)
# Remove the last two entries for the call to extract_stack() and to
# the one before that, this function. Each entry consists of single
# string with consisting of two lines, the script file path then the
# line of source code making the call to this function.
del entries[-2:]
# Split the stack entries on line boundaries.
lines = list(chain.from_iterable(line.splitlines() for line in entries))
if msg: # Append it to last line with name of caller function.
lines[-1] += ' <-- ' + msg
lines.append('LEAVING STACK_DUMP' + (': '+id) if id else '')
print('\n'.join(lines))
print()
sys.modules[__name__] = stackdump # Make a callable module.
if __name__ == '__main__':
import stackdump
def func1():
stackdump('A')
def func2():
func1()
func1()
print()
func2()
How to print the current Stack Trace in .NET without any exception?
Have a look at the System.Diagnostics
namespace. Lots of goodies in there!
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
This is really good to have a poke around in to learn what's going on under the hood.
I'd recommend that you have a look into logging solutions (Such as NLog, log4net or the Microsoft patterns and practices Enterprise Library) which may achieve your purposes and then some.
Print current stack trace in JavaScript
This line of code gets a stack trace and prints it:
console.trace();
Source: https://developer.mozilla.org/en-US/docs/Web/API/Console/trace
Determining Current Call Stack (For Diagnostic Purposes)
I think you can get the same thing with:
StackTraceElement[] cause = Thread.currentThread().getStackTrace();
Related Topics
Identifying Objects, Why Does the Returned Value from Id(...) Change
Python Requests.Exceptions.Sslerror: Eof Occurred in Violation of Protocol
Can You Give a Django App a Verbose Name for Use Throughout the Admin
How to Check If a Column Exists in Pandas
How to Write String Literals in Python Without Having to Escape Them
Comparing Two .Txt Files Using Difflib in Python
Failedpreconditionerror: Attempting to Use Uninitialized in Tensorflow
Image Segmentation Based on Edge Pixel Map
How to Merge Two Dataframes Side-By-Side
Editing Workbooks with Rich Text in Openpyxl
Unbuffered Stdout in Python (As in Python -U) from Within the Program
How to Call an External Program in Python and Retrieve the Output and Return Code
Rreplace - How to Replace the Last Occurrence of an Expression in a String