w3resource

Python: Print the current call stack


Print Call Stack

Write a Python program to print the current call stack.

Sample Solution:

Python Code:

 # Import the 'traceback' module.
import traceback

# Print an empty line for formatting.
print()

# Define a function 'f1' that calls the 'abc' function.
def f1():
    return abc()

# Define the 'abc' function that prints the current stack using 'traceback.print_stack()'.
def abc():
    traceback.print_stack()

# Call the 'f1' function, which, in turn, calls the 'abc' function.
f1()

# Print an empty line for formatting.
print()

Sample Output:

File "7a070e70-25c4-11e7-bc90-3fdc1ec1c64d.py", line 5, in <module>                                         
    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() 
	

Flowchart:

Flowchart: Print the current call stack.

For more Practice: Solve these Related Problems:

  • Write a Python program to capture and log the function call stack dynamically.
  • Write a Python program to print the call stack inside a recursive function.
  • Write a Python program to retrieve the function name that is currently executing.
  • Write a Python program to print the last function call before a program crashes.

Go to:


Previous: Write a Python program to check if a string is numeric.
Next: Write a Python program to list the special variables used within the language.

Python Code Editor:

 

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.