Print current call stack from a method in Python code

在Python中,如何从方法内打印当前调用堆栈(用于调试目的)。


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.


import traceback
traceback.print_stack()

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.

链接地址: http://www.djcxy.com/p/82428.html

上一篇: 在Ruby中获取当前堆栈跟踪而不引发异常

下一篇: 从Python代码中的方法打印当前调用堆栈