获得一个没有异常的python回溯

Ben*_*ey4 12 python pretty-print stack-trace

假设你有这些模块:

module1.py

import module2

def a():
    module1.b()

def c():
    print "Hi guys!"
Run Code Online (Sandbox Code Playgroud)

module2.py

import module1

def b():
    module1.c()
Run Code Online (Sandbox Code Playgroud)

我想要一个func(a())产生类似输出的函数:(=一个追溯?)

 /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!"
Run Code Online (Sandbox Code Playgroud)

有可能使用标准模块traceback和/或cgitb和/或inspect我很难从文档中找出这些模块.

我认为它可以做,traceback.print_stack(a())但它只是因为某种原因而一直在加载.我尝试了这些模块中的其他功能但没有成功.

更新3

@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()')
Run Code Online (Sandbox Code Playgroud)

我什么时候做: python trapy_module.py我得到:

--- modulename: trapy, funcname: <module>
<string>(1): 
Run Code Online (Sandbox Code Playgroud)

更换import randomimport pygletrandom.random()pyglet.app.run()只是不断没有任何输出运行.

jte*_*ace 15

traceback.print_stack很适合我:

>>> 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
Run Code Online (Sandbox Code Playgroud)

更新:

你已经明确表示你真的不想追溯.您想要跟踪信息.这是一种可以获得一些跟踪信息的方法:

#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()
Run Code Online (Sandbox Code Playgroud)

并运行以上:

$ 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
Run Code Online (Sandbox Code Playgroud)