Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print python stack trace without exception being raised

People also ask

How do I print a stack trace?

Just use new Throwable(). printStackTrace() method and it will print complete stack trace from where a method is called, into the console.

How do I fix Python traceback error?

If there is no variable defined with that name you will get a NameError exception. To fix the problem, in Python 2, you can use raw_input() . This returns the string entered by the user and does not attempt to evaluate it. Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.


traceback.print_stack():

>>> def f():
...   def g():
...     traceback.print_stack()
...   g()
...
>>> f()
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in f
  File "<stdin>", 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(...)))


Instead of printing to stdout, if you need a string to pass to a logger you can use:

''.join(traceback.format_stack())

Note, that traceback.format_stack() returns the stacktrace as a formatted list of strings, so you can slice it anyway you want. To get the last few elements of the stacktrace you could do:

''.join(traceback.format_stack()[-N:])

Where N is the number of levels you are interested in.