fork download
  1. import sys
  2.  
  3. def profiler(frame, event, arg):
  4. if event == 'call':
  5. print(f"[ENTER] Context: {frame.f_code.co_name}")
  6. elif event == 'return':
  7. print(f"[EXIT] Context: {frame.f_code.co_name}")
  8.  
  9. def print_call_stack_decorator(func):
  10. def wrapper(*args, **kwargs):
  11. orig_profile = sys.getprofile()
  12. sys.setprofile(profiler)
  13. value = func(*args, **kwargs)
  14. sys.setprofile(orig_profile)
  15. return value
  16. return wrapper
  17.  
  18. def c():
  19. print("c")
  20.  
  21. def b():
  22. c()
  23. print('b')
  24.  
  25. @print_call_stack_decorator
  26. def a():
  27. b()
  28. print('a')
  29.  
  30. a()
Success #stdin #stdout 0.13s 14112KB
stdin
Standard input is empty
stdout
[ENTER] Context: a
[ENTER] Context: b
[ENTER] Context: c
c
[EXIT] Context: c
b
[EXIT] Context: b
a
[EXIT] Context: a