print python stack trace without exception being raised

后端 未结 2 1347
情话喂你
情话喂你 2020-12-07 18:43

Something is happening with one of my class\'s instance variables. I want to make the variable a property, and whenever it is accessed I want to print out the stack trace of

2条回答
  •  长情又很酷
    2020-12-07 19:11

    traceback.print_stack():

    >>> def f():
    ...   def g():
    ...     traceback.print_stack()
    ...   g()
    ...
    >>> f()
      File "", line 1, in 
      File "", line 4, in f
      File "", line 3, in g
    

    Edit: You can also use extract_stack, take a slice (e.g. stack[5:] for exclude the first 5 levels) and use format_list to get a print-ready stacktrace ('\n'.join(traceback.format_list(...)))

提交回复
热议问题