Getting a python traceback without an exception

前端 未结 1 1653
故里飘歌
故里飘歌 2021-02-07 15:46

Suppose you have these modules:

module1.py

import module2

def a():
    module1.b()

def c():
    print \"Hi guys!\"

module2.py

1条回答
  •  遥遥无期
    2021-02-07 16:24

    traceback.print_stack works nicely for me:

    >>> import traceback
    >>> def what():
    ...    traceback.print_stack()
    ... 
    >>> def hey():
    ...    what()
    ... 
    >>> hey()
      File "", line 1, in 
      File "", line 2, in hey
      File "", 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: 
    (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
    

    0 讨论(0)
提交回复
热议问题