Python: Print the current call stack
Write a Python program to print the current call stack.
Sample Solution:-
Python Code:
import traceback print() def f1():return abc() def abc():traceback.print_stack() f1() print()
File "7a070e70-25c4-11e7-bc90-3fdc1ec1c64d.py", line 5, in f1() File "7a070e70-25c4-11e7-bc90-3fdc1ec1c64d.py", line 3, in f1 def f1():return abc() File "7a070e70-25c4-11e7-bc90-3fdc1ec1c64d.py", line 4, in abc def abc():traceback.print_stack()
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
Follow us on Facebook and Twitter for latest update.
Python: Tips of the Day
Converting string into datetime:
datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:
from datetime import datetime datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
The resulting datetime object is timezone-naive.
- Python documentation for strptime: Python 2, Python 3
- Python documentation for strptime/strftime format strings: Python 2, Python 3
- strftime.org is also a really nice reference for strftime
- strptime = «string parse time»
- strftime = «string format time»
- Pronounce it out loud today & you won’t have to search for it again in 6 months.
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
Python Program to Print Stack Trace
A stack trace , also known as stack traceback , traceback, or backtrace, prints all the function calls that took place before an error occurred. Python Print Stack Trace assists users in figuring out the cause of an error and solving it.
What is Stack Trace in Python?
A stack trace is used to display all the function calls before an error occurs. The error is reported on the final line of the stack trace. The stack trace also shows information and function calls related to the thrown error to help users locate and solve it.
How to Print Stack Trace in Python?
Method 1: Using print_exc()
In the following code snippet, the value of the denominator is set to 0 to view how Python print stack trace works. The traceback.print_exc() method in the except block prints the program’s location, the line where the error was encountered, and the name and relevant information about the error. The last line confirms that the entire code executes without hindrance.
Method 2: Using print_exception()
In the following example, since the list arr has indices from 0-4 trying to address index 5 throws an error. The traceback.print_exception(*sys.exc_info()) method in the except block prints the details and cause of the error. The last line printed confirms that the entire code executes successfully.
More Examples for Understanding
Example 1
In the following erroneous code snippet, blood_group is written as bloodgroup to see how Python print stack trace works. The displayed stack trace contains information about the type of error — NameError, that occurred because the referenced variable bloodgroup is not defined. The exception tells us that the variable, function, or class does not exist due to incorrect reference.
Example 2
In the following code snippet, the value for children is set to 0 to view how Python print stack trace works. The displayed stack trace contains information about the type of error — ZeroDivisionError, that occurred because the denominator is 0 .
Example 3
In the following example, since the list arr has indices from 0-4 trying to address index 5 throws an error. The traceback.print_exception(*sys.exc_info()) method in the except block prints the details and cause of the error. This example is used to add more depth to the stack for easy visualization. Initially the function h() is called followed by g() and finally f() where trying to address index 5 throws an error.
FAQs
Q: Which module is required for Python print stack trace?
A: Importing the traceback module helps to extract, format and print stack traces.
Q: What does a stack trace show?
A: A stack trace displays the call stack (set of active method calls) and provides information about the methods called before an error occurs. It helps developers to figure out what went wrong in the code.
Q: What information does the stack trace contain? The stack trace contains :
- Traceback for the most recent call.
- Location of the program.
- Erroneous Line.
- Type of error and relevant information.
Q: What is the difference between print_exc and print_exception?
print_exc | print_exception |
---|---|
traceback.print_exc(limit=None, file=None, chain=True) | traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True) |
It accepts 3 parameters limit , file , and chain . | It accepts 6 parameters etype , value , tb , limit , file , chain |
Conclusion
- In Python print stack trace to see the function calls that took place before an error occurred.
- The stack trace information helps to locate and fix the error easily.
- The traceback module in Python provides functionalities to deal with the stack trace.
- The methods used to print stack trace are print_exception() and print_exc() .