2

If I have a traceback such as:

 Traceback (most recent call last):
  File "...\overall_input.py", line 5, in setup_data
    MODULE1.function_name()
  File "...\MODULE1.py", line 5, in function_name
    value = 1/0

How do I get the name of the second file deep - i.e. MODULE1.py?

For reference, I know I can get the first file (i.e. overall_input.py) by capturing the exception and then using:

exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]

as described in the answer Python When I catch an exception, how do I get the type, file, and line number? .

Community
  • 1
  • 1
kyrenia
  • 5,431
  • 9
  • 63
  • 93

1 Answers1

4

You need to access the same attributes after going towards the frame that raised the exception by using tb_next on exc_tb:

exc_tb.tb_next.tb_frame.f_code.co_filename

tb_next is another traceback object that contains identical attributes as the previous; it's just a chain which you can follow until you reach the level you need.


Even though I've never used it, I'm certain the traceback module would be quite handy if you're doing weird things with them.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253