Git Product home page Git Product logo

backtrace's Introduction

backtrace

WIP! Untested!

Travis Build Status AppVeyor Build Status PyPI Version Supported Python Versions Requirements Status Code Coverage Code Quality Is Wheel

backtrace manipulates Python tracebacks to make them more readable. It provides different configuration options for coloring and formatting.

backtrace also allows to choose the formatting of each part of the traceback; show the traceback entries in reversed order, and more..

Examples:

When piping to backtrace:

Trump? REALLY?! What a nation of idiots!

When using the API directly from Python:

Trump? REALLY?! What a nation of idiots!

NOTE: Didn't test this on Windows yet. Should work.. but don't know how well.

Alternatives

  • colored_traceback provides a way to color your tracebacks to make them more readable. It's a nice little tool but lacks actually re-formatting the traceback which is what the biggest problem is from my POV.
  • Um.. your own implementation? There's really a reason for me doing this. I do have a life you know (well.. I try anyway).

Installation

backtrace officially supports Linux and OSX on Python 2.7 and 3.4+. Python 2.6 will also probably work, but with no guarantees.

pip install backtrace

For dev:

pip install https://github.com/nir0s/backtrace/archive/master.tar.gz

Usage

backtrace provides two methods for manipulating your tracebacks.

  • Piping to backtrace using its CLI
  • Using backtrace from within your code

Piping

You can pipe stderr into backtrace which will try to detect a traceback, parse it and display a beautified trace.

$ backtrace -h
usage: backtrace [-h] [-r] [-a] [-s] [-c]

Beautify Tracebacks.

Just pipe stderr into backtrace like so:
  `python bad-program.py 2>&1 | backtrace`

optional arguments:
  -h, --help          show this help message and exit
  -r, --reverse       Reverse traceback entry order
  -a, --align         Right-align the backtrace
  -s, --strip-path    Strip the path to the module
  -c, --conservative  Activate conservative mode

$ python my-traceback-generating-program.py 2>&1 | backtrace
...

Inside your application

import backtrace

backtrace.hook(
    reverse=False,
    align=False,
    strip_path=False,
    enable_on_envvar_only=False,
    on_tty=False,
    conservative=False,
    styles={})

# more code...

# if you wanna restore the default hook...
backtrace.unhook()
...

You can pass the following flags to hook to change backtrace's behavior:

  • If reverse is True, the traceback entries will be printed in reverse order.
  • If align is True, all parts (line numbers, file names, etc..) will be aligned to the left according to the longest entry. This allows for extended readability as your eyes don't have to move between columns to understand what's going on.
  • If strip_path is True, only the file name will be shown, not its full path. This is useful when you know you're running in the context of a single module or a single package containing only a root folder so you only need file names. This can help keep the traceback clean.
  • If enable_on_envvar_only is True, only if the environment variable ENABLE_BACKTRACE is set, backtrace will be activated.
  • If on_tty is True, backtrace will be activated only if you're running in a real terminal (i.e. not piped, redirected, etc..). This can help keep the original traceback when logging to files or piping to look for information.
  • styles is a dictionary containing the styling for each part of the rebuilt traceback. See below.
  • If conservative is true, a more conservative format will be provided for people who find the default backtrace style too new or intimidating. For example, no alignment will be done (unless align is explicitly passed), styles will be ignored, and potential unnecessary data will be retained. Try It! It's still eye-candy.

Styles

Styles allow you to customize the coloring and structure of your new traceback. The defaults are:

STYLES = {
    'backtrace': Fore.YELLOW + '{0}',
    'error': Fore.RED + Style.BRIGHT + '{0}',
    'line': Fore.RED + Style.BRIGHT + '{0}',
    'module': '{0}',
    'context': Style.BRIGHT + Fore.GREEN + '{0}',
    'call': Fore.YELLOW + '--> ' + Style.BRIGHT + '{0}',
}

Where:

  • backtrace is the main traceback message.
  • error is the error message presenting the exception message and its type.
  • line is the line number of each entry.
  • module is the calling module of each entry.
  • context is the calling function/method of each entry.
  • call is the called function/method/assignment of each entry.

and the {0} format place holder is the actual value of the field.

Sending a partial dictionary containing changes in only some parts of the traceback will have backtrace use the defaults for whatever wasn't specified.

You can do all sorts of stuff like removing a certain field by setting the formatting of that field to an empty string; add more verbose identifiers to each field by appending an ID in front of it or just adding paranthese around a field.

Coloring

Coloring is powered by colorama.

Testing

To see an example printout:

$ python test.py
git clone [email protected]:nir0s/backtrace.git
cd backtrace
pip install tox
tox

Contributions..

See CONTRIBUTIONS

Pull requests are always welcome..

backtrace's People

Contributors

kammeyer avatar nir0s avatar t184256 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

backtrace's Issues

Backtrace piping doesn't work in Python 3

The output of an exception that isn't parsed well:

Traceback (most recent call last):
  File "/home/nir0s/repos/nir0s/backtrace/test2.py", line 4, in moose_bites_kan_be_pretty_nasti
    with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'certainly_a_non_existing_moose'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 123, in <module>
    i = Moose()
  File "test.py", line 25, in __init__
    self.a_moose_once_bit_my_sister()
  File "test.py", line 28, in a_moose_once_bit_my_sister
    _mynd_you()
  File "test.py", line 118, in _mynd_you
    test2.moose_bites_kan_be_pretty_nasti()
  File "/home/nir0s/repos/nir0s/backtrace/test2.py", line 10, in moose_bites_kan_be_pretty_nasti
    moose_func(ex)
  File "/home/nir0s/repos/nir0s/backtrace/test2.py", line 14, in moose_func
    raise raise_moose(ex)
  File "/home/nir0s/repos/nir0s/backtrace/test2.py", line 18, in raise_moose
    raise MooseError(ex)
test2.MooseError: [Errno 2] No such file or directory: 'certainly_a_non_existing_moose'

Calling colorama.init(autoreset=True) causes problems

I don't want colorama autoreset=True. Why are you pushing this on me?
You should call colorama.init() if you have to, but reset colors as you require.
I should be able to set autoreset as I prefer, your stuff should work either way.

Frames local variables

It would be amazing to see local variables in each frame of the traceback. It really helps debugging!

potential parsing error

Thank you so much for this utility it helps me a lot! It appears that there's some problem with parsing. See the original traceback (Figure 1) and the parsed traceback (Figure 2). The black squares cover the same file path. The reason why I feel there might be problems is that the yellow bold text after the arrow appears not very consistent with each other. It should be respectively "in main", "in run_divg_...", etc., instead of "in main", "control=2)", etc., from my point of view. Thanks!

Figure 1:
orig_tb

Figure 2:
parsed_tb

Simply running `backtrace`, results in a hung process

When running backtrace without providing it with any input from stdin, backtrace will try to read it but hang because nothing goes through. Instead, it should be first test to see that stdin isn't empty and exit if it is.

why colorama==0.3.7?

The colorama dependency is specified as colorama==0.3.7. Is there a reason for such strictness or may I just override it and use it with, e.g., 0.3.9?

Backtrace does not handle nested exceptions

In python3, running the following will result in backtrace not identifying a traceback:

try:
    raise Exception
except Exception:
    _, __, tb = sys.exc_info()
    raise Exception(tb)
$ python test.py 2>&1 | backtrace

Publish new version

The issue backtrace requires colorlama==0.3.7 is fixed but not published. My package is dependent on backtrace and it prints the version conflict error when installing. Please consider publishing new version.

Discards standard output

I often want to view stdout as well, and it would be nice if backtrace let that be printed as is.

Backtrace doesn't work with Django

Thank you for developing this package. I am glad to have found it.
My issue is that I wasn't able to use it, just out of the box.

I just ran $ python manage.py migrate | backtrace but I got an error that says:

django.db.utils.OperationalError: no such table: accounts_user
No Traceback detected. Make sure you pipe stderr to backtrace correctly.

Let me know if I can provide further details.
Cheers.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.