Python traceback line number

Traceback in Python

Traceback is a python module that provides a standard interface to extract, format and print stack traces of a python program. When it prints the stack trace it exactly mimics the behaviour of a python interpreter. Useful when you want to print the stack trace at any step. They are usually seen when an exception occurs. Since a traceback gives all the information regarding the exception it becomes easier to track one and fix it.

General structure of a stack trace for an exception:

Traceback for most recent call Location of the program Line in the program where error was encountered Name of the error: relevant information about the exception
Traceback (most recent call last): File "C:/Python27/hdg.py", line 5, in value = A[5] IndexError: list index out of range

The module uses traceback objects, this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info() .

Functions in the Module

  • traceback.print_tb(tb, limit = None, file = None) : If limit is positive it prints upto limit stack trace entries from traceback object tb. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output.
  • traceback.print_exception(etype, value, tb, limit = None, file = None, chain = True) : Prints exception information and stack trace entries from traceback object tb to file. If tb is not None, it prints a header Traceback (most recent call last): . It prints the exception etype and value after the stack trace. If type(value) is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret indicating the approximate position of the error.
  • traceback.print_exc(limit = None, file = None, chain = True) : This is a shorthand for print_exception(*sys.exc_info(), limit, file, chain).
  • traceback.print_last(limit = None, file = None, chain = True) : It works only after an exception has reached an interactive prompt. This is a shorthand for print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain).
  • traceback.print_stack(f = None, limit = None, file = None) : If limit is positive, prints up to limit stack trace. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start.
  • traceback.extract_tb(tb, limit = None) : Returns a StackSummary object representing a list of “pre-processed” stack trace entries (FrameSummary object containing attributes filename, lineno, name, and line) extracted from the traceback object tb. It is useful for alternate formatting of stack traces.
  • traceback.extract_stack(f = None, limit = None) : Extracts the raw traceback from the current stack frame. The return value has the same format as for extract_tb().
  • traceback.format_list(extracted_list) : Given a list of tuples or FrameSummary objects returns a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well.
  • traceback.format_exception_only(etype, value) : Formats the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. It returns a list of strings each ending in a new line.
  • traceback.format_exception(etype, value, tb, limit = None, chain = True) : Formats stack trace and exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). It returns a list of strings each ending in new line and some have internal newlines too. When these lines are concatenated and printed they generate an exactly same output as print_exception().
  • traceback.format_exc(limit = None, chain = True) : This is like print_exc(limit) except it returns a string instead of printing to a file.
  • traceback.format_tb(tb, limit = None) : shorthand for format_list(extract_tb(tb, limit)).
  • traceback.format_stack(f = None, limit = None) : shorthand for format_list(extract_stack(f, limit)).
  • traceback.clear_frames(tb) : Clears the local variables of all stack frames in a traceback tb by calling clear() method of each frame object.
  • traceback.walk_stack(f) : Walk a stack following f.f_back from the given frame, yielding the frame and line number for each frame. If f is None, the current stack is used. This helper is used with StackSummary.extract().
  • traceback.walk_tb(tb) : Walk a traceback following tb_next yielding the frame and line number for each frame. This helper is used with StackSummary.extract().
Читайте также:  Html изменить цвет маркера

Example : Program that prints the exception stack trace.

Источник

How to read a traceback in Python

Sign in to your Python Morsels account to save your screencast settings.

When Python encounters an error in your code, it will print out a traceback. Let’s talk about how to use tracebacks to fix our code.

Traceback (most recent call last)?

Here we have a program called count.py :

import sys def count_to(number): for n in range(1, number+1): print(n) def main(): stop = sys.argv[1] count_to(stop) if __name__ == "__main__": main() 

This program is supposed to accept a number and print out all the numbers up to and including that number.

But this code is broken. When we run it, it prints out a traceback:

$ python3 count.py 5 Traceback (most recent call last): File "/home/trey/count.py", line 12, in main() File "/home/trey/count.py", line 9, in main count_to(stop) File "/home/trey/count.py", line 4, in count_to for n in range(1, number+1): TypeError: can only concatenate str (not "int") to str 

When Python encounters an exception that isn’t handled in your code, it will print out a traceback.

Read the last line in a traceback first

Tracebacks are supposed to be read from the bottom upward: the very last line in a traceback is the first line that you’re supposed to read.

That last line in the traceback describes the type of exception that occurred, and it shows us an error message that’s supposed to explain what happened:

TypeError: can only concatenate str (not "int") to str 

The error message shown in tracebacks can sometimes be a little bit cryptic, but it’s typically better than nothing.

After that last line, we’re supposed to read the two lines above that:

 File "/home/trey/count.py", line 4, in count_to for n in range(1, number+1): 

And then the two lines above that:

 File "/home/trey/count.py", line 9, in main count_to(stop) 

And so on. That’s why the first line in a traceback says most recent call last: the most recent call in our code is the last line in the traceback).

We read tracebacks from the bottom upward.

The two lines above that last one describe where we actually were in our code when the exception occurred:

 File "/home/trey/count.py", line 4, in count_to for n in range(1, number+1): 

We were in count.py , on line 4 , in the count_to function (note that you can see the actual line of code in that file as well).

The lines in a traceback represent frames in the «call stack»

Python uses something called a call stack to keep track of where you are in your Python process at any one time. It keeps track of where you’re supposed to go next when you return from your current function, where that function will return to, and so on.

The lines in our traceback describe our call stack. That is, they describe where Python actually was in our process when the exception occurred:

 File "/home/trey/count.py", line 12, in main() File "/home/trey/count.py", line 9, in main count_to(stop) File "/home/trey/count.py", line 4, in count_to for n in range(1, number+1): 

Each of those sets of two lines are called stack frames. You can think of Stack frames as levels of depth in our code: the bottom-most two lines in our traceback represents the deepest level, while the top-most lines represent the furthest level out from where that exception occurred.

So in our count.py program, line 4 is where the exception actually occurred:

 File "/home/trey/count.py", line 4, in count_to for n in range(1, number+1): 

Because tracebacks represent lines in the call stack, they’re also sometimes called a stack trace.

In general, the deepest stack frame in our traceback won’t always be our code (that is code we wrote). It could be code from some other module besides our own. So sometimes you’ll need to read other frames in your call stack above that bottom one.

Reading up the call stack to fix the bug

Now, I happen to know that what this TypeError means:

TypeError: can only concatenate str (not "int") to str 

That error message means Python tried to use the + operator between a string and an integer, and that’s not allowed. See the article TypeError: can only concatenate str (not «int») to str for more details.

The exception occurred on line 4, in number+1 :

import sys def count_to(number): for n in range(1, number+1): print(n) 

The number variable must be pointing to a string (since 1 is an integer).

We probably shouldn’t convert number to an integer in this function, because this function isn’t supposed to accept strings. Let’s go up to the next frame in our call stack!

The next frame in our call stack here is on line 9 :

 File "/home/trey/count.py", line 9, in main count_to(stop) File "/home/trey/count.py", line 4, in count_to for n in range(1, number+1): 

This function is where we could fix this error:

def main(): stop = sys.argv[1] count_to(stop) 

The line just above count_to(stop) , line 8, is where we should convert that string to a number. The command line argument ( sys.argv[1] ) is coming in as a string, so we should convert it to a number (by passing it to the int function) before pointing the stop variable to it:

def main(): stop = int(sys.argv[1]) count_to(stop) 

This should fix the bug in our code. Let’s try and run our count.py program again:

$ python3 count.py 5 1 2 3 4 5 

It works! We’ve just fixed the bug.

Read tracebacks from the bottom upward

Tracebacks happen all the time. Reading tracebacks is just part of the process of writing Python code. Whenever Python encounters an unhandled exception in your code, it’ll print out a traceback.

Remember, tracebacks should be read from the bottom upward. The last line tells you the exception that occurred and a (hopefully helpful) error message. That last line is what you might want to type into your favorite search engine to figure out what might be going on.

Then the two lines above the last one tell you what line the exception actually occurred on. Then from there, each set of two lines describes the next level of depth in our code (a.k.a. stack frames).

Remember: read your tracebacks from the bottom upward.

What comes after Intro to Python?

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I’ll explain concepts that new Python programmers often overlook.

Series: Exceptions

Exceptions happens! When exceptions happen, how should interpret the traceback for an exception? And how, when, and where should you catch exceptions?

To track your progress on this Python Morsels topic trail, sign in or sign up.

Источник

Оцените статью