Python traceback with variables

traceback — Print or retrieve a stack traceback¶

This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter.

The module uses traceback objects — these are objects of type types.TracebackType , which are assigned to the __traceback__ field of BaseException instances.

Used to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal.

Interactive source code debugger for Python programs.

The module defines the following functions:

traceback. print_tb ( tb , limit = None , file = None ) В¶

Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame) if limit is positive. 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.

Changed in version 3.5: Added negative limit support.

Print exception information and stack trace entries from traceback object tb to file. This differs from print_tb() in the following ways:

if tb is not None , it prints a header Traceback (most recent call last):

it prints the exception type 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.

Since Python 3.10, instead of passing value and tb, an exception object can be passed as the first argument. If value and tb are provided, the first argument is ignored in order to provide backwards compatibility.

The optional limit argument has the same meaning as for print_tb() . If chain is true (the default), then chained exceptions (the __cause__ or __context__ attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception.

Changed in version 3.5: The etype argument is ignored and inferred from the type of value.

Changed in version 3.10: The etype parameter has been renamed to exc and is now positional-only.

This is a shorthand for print_exception(sys.exception(), limit, file, chain) .

traceback. print_last ( limit = None , file = None , chain = True ) В¶

This is a shorthand for print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain) . In general it will work only after an exception has reached an interactive prompt (see sys.last_type ).

traceback. print_stack ( f = None , limit = None , file = None ) В¶

Print up to limit stack trace entries (starting from the invocation point) if limit is positive. 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. The optional file argument has the same meaning as for print_tb() .

Changed in version 3.5: Added negative limit support.

Return a StackSummary object representing a list of “pre-processed” stack trace entries extracted from the traceback object tb. It is useful for alternate formatting of stack traces. The optional limit argument has the same meaning as for print_tb() . A “pre-processed” stack trace entry is a FrameSummary object containing attributes filename , lineno , name , and line representing the information that is usually printed for a stack trace. The line is a string with leading and trailing whitespace stripped; if the source is not available it is None .

traceback. extract_stack ( f = None , limit = None ) В¶

Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb() . The optional f and limit arguments have the same meaning as for print_stack() .

traceback. format_list ( extracted_list ) В¶

Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack() , return 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, for those items whose source text line is not None .

traceback. format_exception_only ( exc , / [ , value ] ) В¶

Format the exception part of a traceback using an exception value such as given by sys.last_value . The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list.

Since Python 3.10, instead of passing value, an exception object can be passed as the first argument. If value is provided, the first argument is ignored in order to provide backwards compatibility.

Changed in version 3.10: The etype parameter has been renamed to exc and is now positional-only.

Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception() . The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception() .

Changed in version 3.5: The etype argument is ignored and inferred from the type of value.

Changed in version 3.10: This function’s behavior and signature were modified to match print_exception() .

This is like print_exc(limit) but returns a string instead of printing to a file.

traceback. format_tb ( tb , limit = None ) В¶

A shorthand for format_list(extract_tb(tb, limit)) .

traceback. format_stack ( f = None , limit = None ) В¶

A shorthand for format_list(extract_stack(f, limit)) .

traceback. clear_frames ( tb ) В¶

Clears the local variables of all the stack frames in a traceback tb by calling the clear() method of each frame object.

New in version 3.4.

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() .

New in version 3.5.

Walk a traceback following tb_next yielding the frame and line number for each frame. This helper is used with StackSummary.extract() .

New in version 3.5.

The module also defines the following classes:

TracebackException Objects¶

New in version 3.5.

TracebackException objects are created from actual exceptions to capture data for later printing in a lightweight fashion.

class traceback. TracebackException ( exc_type , exc_value , exc_traceback , * , limit = None , lookup_lines = True , capture_locals = False , compact = False ) В¶

Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.

If compact is true, only data that is required by TracebackException ’s format method is saved in the class attributes. In particular, the __context__ field is calculated only if __cause__ is None and __suppress_context__ is false.

Note that when locals are captured, they are also shown in the traceback.

A TracebackException of the original __cause__ .

A TracebackException of the original __context__ .

The __suppress_context__ value from the original exception.

The __notes__ value from the original exception, or None if the exception does not have any notes. If it is not None is it formatted in the traceback after the exception string.

New in version 3.11.

A StackSummary representing the traceback.

The class of the original traceback.

For syntax errors — the file name where the error occurred.

For syntax errors — the line number where the error occurred.

For syntax errors — the text where the error occurred.

For syntax errors — the offset into the text where the error occurred.

For syntax errors — the compiler error message.

classmethod from_exception ( exc , * , limit = None , lookup_lines = True , capture_locals = False ) В¶

Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.

Note that when locals are captured, they are also shown in the traceback.

print ( * , file = None , chain = True ) В¶

Print to file (default sys.stderr ) the exception information returned by format() .

New in version 3.11.

Format the exception.

If chain is not True , __cause__ and __context__ will not be formatted.

The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file.

The message indicating which exception occurred is always the last string in the output.

Format the exception part of the traceback.

The return value is a generator of strings, each ending in a newline.

Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred.

The message indicating which exception occurred is always the last string in the output.

Changed in version 3.10: Added the compact parameter.

StackSummary Objects¶

New in version 3.5.

StackSummary objects represent a call stack ready for formatting.

class traceback. StackSummary В¶ classmethod extract ( frame_gen , * , limit = None , lookup_lines = True , capture_locals = False ) В¶

Construct a StackSummary object from a frame generator (such as is returned by walk_stack() or walk_tb() ).

If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is False , the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper (which may be valuable if it may not actually get formatted). If capture_locals is True the local variables in each FrameSummary are captured as object representations.

classmethod from_list ( a_list ) В¶

Construct a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements.

Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines.

For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions.

Changed in version 3.6: Long sequences of repeated frames are now abbreviated.

Returns a string for printing one of the frames involved in the stack. This method is called for each FrameSummary object to be printed by StackSummary.format() . If it returns None , the frame is omitted from the output.

New in version 3.11.

FrameSummary Objects¶

New in version 3.5.

A FrameSummary object represents a single frame in a traceback.

class traceback. FrameSummary ( filename , lineno , name , lookup_line = True , locals = None , line = None ) В¶

Represent a single frame in the traceback or stack that is being formatted or printed. It may optionally have a stringified version of the frames locals included in it. If lookup_line is False , the source code is not looked up until the FrameSummary has the line attribute accessed (which also happens when casting it to a tuple). line may be directly provided, and will prevent line lookups happening at all. locals is an optional local variable dictionary, and if supplied the variable representations are stored in the summary for later display.

Traceback Examples¶

This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module.

The following example demonstrates the different ways to print and format the exception and traceback:

The output for the example would look similar to this:

The following example shows the different ways to print and format the stack:

This last example demonstrates the final few formatting functions:

Источник

traceback-with-variables 2.0.4

pip install traceback-with-variables Скопировать инструкции PIP

Выпущен: 5 дек. 2021 г.

Adds variables to python traceback. Simple, lightweight, controllable. Debug reasons of exceptions by logging or pretty printing colorful variable contexts for each frame in a stacktrace, showing every value. Dump locals environments after errors to console, files, and loggers. Works with Jupiter and IPython.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License

Метки python, traceback, locals, logging, debugging, print, variables, python3, stacktrace, arguments, errors, error-handling, dump, exception-handling, exceptions, pretty, pretty-print, frame, simple, colors, jupyer, jupyer-notebook, ipython, customize

Требует: Python >=3.5

Сопровождающие

Классификаторы

  • Intended Audience
    • Developers
  • License
    • OSI Approved :: MIT License
  • Operating System
    • OS Independent
  • Programming Language
    • Python :: 3
  • Topic
    • Software Development :: Debuggers
    • Software Development :: Libraries

Описание проекта

Python Traceback (Error Message) Printing Variables

Very simple to use, but versatile when needed. Try for debug and keep for production.

“It is useless work that darkens the heart.” – Ursula K. Le Guin

Tired of useless job of putting all your variables into debug exception messages? Just stop it. Automate it and clean your code. Once and for all.

Contents: Installation | 🚀 Quick Start | Colors | How does it save my time? | Examples and recipes | Reference | FAQ

:warning: This module is actively updated and has a substantial list of features to add this week: so any proposal or advice or warning is very welcome and will be taken into account of course. When I started it I wanted to make a tool meeting all standard use cases. I think in this particular domain this is rather achievable, so I’ll try. Note next_version branch also. Have fun!

Installation

🚀 Quick Start

Decorator, for a single function:

Context, for a single code block:

Print traceback in interactive mode after an exception:

Customize any of the previous examples:

Colors

How does it save my time?

Turn a code totally covered by debug formatting from this:

into this (zero debug code):

And obtain total debug info spending 0 lines of code:

Automate your logging too:

Free your exceptions of unnecessary information load:

— Should I use it after debugging is over, i.e. in production?

Yes, of course! That way it might save you even more time (watch out for sensitive data like passwords and tokens in you logs). Note: you can deploy more serious frameworks, e.g. Sentry :)

Stop this tedious practice in production:

step 1: Notice some exception in a production service.
step 2: Add more printouts, logging, and exception messages.
step 3: Rerun the service.
step 4: Wait till (hopefully) the bug repeats.
step 5: Examine the printouts and possibly add some more info (then go back to step 2).
step 6: Erase all recently added printouts, logging and exception messages.
step 7: Go back to step 1 once bugs appear.

Examples and recipes

Reference

All functions have fmt= argument, a Format object with fields:

  • max_value_str_len max length of each variable string, -1 to disable, default=1000
  • max_exc_str_len max length of exception, should variable print fail, -1 to disable, default=10000
  • before number of code lines before the raising line, default=0
  • after number of code lines after the raising line, default=0
  • ellipsis_ string to denote long strings truncation, default= .
  • skip_files_except use to print only certain files; list of regexes, ignored if empty, default=None
  • brief_files_except use to print variables only in certain files; list of regexes, ignored if empty, default=None
  • custom_var_printers list of pairs of (filter, printer); filter is a name fragment, a type or a function or a list thereof; printer returns None to skip a var
  • color_scheme is None or one of ColorSchemes : .none , .common , .nice , .synthwave . None is for auto-detect

activate_by_import

Just import it. No arguments, for real quick use in regular Python.

activate_in_ipython_by_import

Just import it. No arguments, for real quick use in Jupyter or IPython.

global_print_exc

Call once in the beginning of your program, to change how traceback after an uncaught exception looks.

global_print_exc_in_ipython

Call once in the beginning of your program, to change how traceback after an uncaught exception looks.

Prints traceback for a given/current/last (first being not None in the priority list) exception to a file, default= sys.stderr . Convenient for manual console or Jupyter sessions or custom try/except blocks. Note that it can be called with a given exception value or it can auto discover current exception in an except: block or it can auto descover last exception value (long) after try/catch block.

Prints current traceback when no exception is raised.

prints_exc

Function decorator, used for logging or simple printing of scoped tracebacks with variables. I.e. traceback is shorter as it includes only frames inside the function call. Program exiting due to unhandled exception still prints a usual traceback.

printing_exc

Context manager (i.e. with . ), used for logging or simple printing of scoped tracebacks with variables. I.e. traceback is shorter as it includes only frames inside the with scope. Program exiting due to unhandled exception still prints a usual traceback.

LoggerAsFile

A logger-to-file wrapper, to pass a logger to print tools as a file.

iter_exc_lines

Iterates the lines, which are usually printed one-by-one in terminal.

format_exc

Like iter_exc_lines but returns a single string.

iter_cur_tb_lines

Like iter_exc_lines but doesn’t need an exception and prints upper frames..

format_cur_tb

Like iter_cur_tb_lines but returns a single string.

In Windows console crash messages have no colors.

The default Windows console/terminal cannot print [so called ansi] colors, but this is fixable , especially with modern Windows versions. Therefore colors are disabled by default, but you can enable them and check if it works in your case. You can force enable colors by passing —color-scheme common (for complete list of colors pass —help ) console argument.

Windows console prints junk symbols when colors are enabled.

The default Windows console/terminal cannot print [so called ansi] colors, but this is fixable , especially with modern Windows versions. If for some reason the colors are wrongly enabled by default, you can force disable colors by passing —color-scheme none console argument.

Bash tools like grep sometimes fail to digest the output when used with pipes ( | ) because of colors.

Please disable colors by passing —color-scheme none console argument. The choice for keeping colors in piped output was made to allow convenient usage of head , tail , file redirection etc. In cases like | grep it might have issues, in which case you can disable colors.

Output redirected to a file in > output.txt manner has no colors when I cat it.

This is considered a rare use case, so colors are disabled by default when outputting to a file. But you can force enable colors by passing —color-scheme common (for complete list of colors pass —help ) console argument.

activate_by_import or global_print_exc don’t work in Jupyter or IPython as if not called at all.

In Jupyter or IPython you should use activate_in_ipython_by_import or global_print_exc_in_ipython . IPython handles exceptions differently than regular Python.

The server framework ( flask , streamlit etc.) still shows usual tracebacks.

In such frameworks tracebacks are printed not while exiting the program (the program continues running), hence you should override exception handling in a manner proper for the given framework. Please address the flask example.

How do I reduce output? I don’t need all files or all variables.

Use skip_files_except , brief_files_except , custom_var_printers to cut excess output.

I have ideas about good colors.

Please fork, add a new ColorScheme to ColorSchemes and create a Pull Request to next_version branch. Choose the color codes and visually test it like python3 -m traceback_with_variables.main —color-scheme examples/for_readme_image.py .

My code doesn’t work.

Please post your case. You are very welcome!

Other questions or requests to elaborate answers.

Источник

Adblock
detector