Giter Club home page Giter Club logo

pretty-traceback's Introduction

Human readable stacktraces for Python.

Project/Repo:

MIT License Supported Python Versions CalVer 2023.1020 PyPI Version PyPI Downloads

Code Quality/CI:

GitHub Build Status GitLab Build Status Type Checked with mypy Code Coverage Code Style: sjfmt

Overview

Pretty Traceback groups together what belongs together, adds coloring and alignment. All of this makes it easier for you to see patterns and filter out the signal from the noise. This tabular format is best viewed in a wide terminal.

In other words, get this 😍

logo

Instead of this 🤮

Traceback (most recent call last):
  File "test/test_formatting.py", line 199, in <module>
    main()
  File "test/test_formatting.py", line 190, in main
    run_pingpong()
  File "test/test_formatting.py", line 161, in run_pingpong
    sched3.run()
  File "/home/mbarkhau/miniconda3/envs/pretty-traceback_py38/lib/python3.8/sched.py", line 151, in run
    action(*argument, **kwargs)
  File "/home/mbarkhau/miniconda3/envs/pretty-traceback_py38/lib/python3.8/sched.py", line 151, in run
    action(*argument, **kwargs)
  File "/home/mbarkhau/miniconda3/envs/pretty-traceback_py38/lib/python3.8/sched.py", line 151, in run
    action(*argument, **kwargs)
  File "test/test_formatting.py", line 151, in _ping
    _pong(depth + 1)
  File "test/test_formatting.py", line 129, in _pong
    _ping(depth + 1)
  File "test/test_formatting.py", line 136, in _ping
    sp.check_output(["command_that", "doesnt", "exist"])
  File "/home/mbarkhau/miniconda3/envs/pretty-traceback_py38/lib/python3.8/subprocess.py", line 411, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/home/mbarkhau/miniconda3/envs/pretty-traceback_py38/lib/python3.8/subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/home/mbarkhau/miniconda3/envs/pretty-traceback_py38/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/home/mbarkhau/miniconda3/envs/pretty-traceback_py38/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'command_that'

If your terminal is wide enough, the long paths are preserved.

logo

Usage

Add the following to your __main__.py or the equivalent module which is your entry point.

try:
    import pretty_traceback
    pretty_traceback.install()
except ImportError:
    pass    # no need to fail because of missing dev dependency

Please do not add this code e.g. to your __init__.py or any other module that your users may import. They may not want you to mess with how their tracebacks are printed.

If you do feel the overwhelming desire to import the pretty_traceback in code that others might import, consider using the envvar argument, which will cause the install function to effectively be a noop unless you set ENABLE_PRETTY_TRACEBACK=1.

try:
    import pretty_traceback
    pretty_traceback.install(envvar='ENABLE_PRETTY_TRACEBACK')
except ImportError:
    pass    # no need to fail because of missing dev dependency

Note, that the hook is only installed if the existing hook is the default. Any existing hooks that were installed before the call of pretty_traceback.install will be left in place.

LoggingFormatter

A logging.Formatter subclass is also available (e.g. for integration with flask).

import os
from flask.logging import default_handler

try:
    if os.getenv('FLASK_DEBUG') == "1":
        import pretty_traceback
        default_handler.setFormatter(pretty_traceback.LoggingFormatter())
except ImportError:
    pass    # no need to fail because of missing dev dependency

More Examples

logo

logo

logo

Alternatives

Pretty Traceback is heavily inspired by the backtrace module by nir0s but there are many others (sorted by github stars):

Contributors

Name role since until
Manuel Barkhau ([email protected]) author/maintainer 2020-08 -

pretty-traceback's People

Contributors

mbarkhau avatar iloveitaly avatar julesgm avatar

Stargazers

 avatar ubless607 avatar  avatar Gailey Leseman avatar Leon avatar neimad1985 avatar Greg D avatar  avatar rhcproc avatar IML avatar  avatar Mingdao Liu avatar Alex Norell avatar Nick Muoh avatar  avatar Pramod Laxman avatar Lev Gorodetskii avatar Mohammad Etemaddar avatar Akim avatar  avatar Dmitriy Nyashkin avatar  avatar Nghia avatar Kyle King avatar  avatar Anatoli Babenia avatar Alexander Burchenko avatar Steven Kessler avatar  avatar Petr Hanák avatar Dr Yann Golanski avatar Nikolaus Schlemm avatar Reuben S Varghese avatar  avatar Alberto Sierra avatar Ian Trudel avatar Kobi Cohen-Arazi avatar Gabbeh avatar Nikola Selic avatar LoiHQ avatar  avatar  avatar Roderick Go avatar  avatar  avatar PXLKSR avatar

Watchers

 avatar James Cloos avatar

pretty-traceback's Issues

`LoggingFormatterMixin` calls `os.terminal_size()` which doesn't work when app is not running in TTY

Hi!

I'm using pretty-traceback as part of my application logging. App is deployed inside of a docker container which means app's process is not running in TTY.

When my loggers call formatException from:

class LoggingFormatterMixin(object):

    def formatException(self, ei):
        _, exc_value, traceback = ei
        return exc_to_traceback_str(exc_value, traceback, color=True)

I get "stty: standard input: Not a tty" message. This is because of following call chain:

exc_to_traceback_str() 
    --> _get_terminal_width() 
        --> os.get_terminal_size()

Current workaround for me is adding environment variable COLUMNS. It effectively prevents call to os.get_terminal_size.

This is fine, but is not perfect 😊 .

I would like to avoid adding COLUMNS env variable and would like to instead do this through code. Something like this would work for me, but any other solution that let's me somehow avoid call to os.get_terminal_size() is also fine:

- def exc_to_traceback_str(exc_value, traceback, color=False):
+ def exc_to_traceback_str(exc_value, traceback, color=False, columns=None):
  • when columns is not None, use that, ignore os.environ["COLUMNS"] and don't call os.get_terminal_size()
  • when columns is None keep current behavior

Output lacks final linefeed

In a Linux environment, pretty-traceback is fantastic, except that for me it isn't issuing a final linefeed, leaving my prompt appended to the end of the final line of output.

A quick peek at the code suggests to me that this is to be expected, owing to use of sys.stderr.write() in hook.py, though I'm unclear if this behavior is intentional or not.

Assuming it isn't intentional, and hoping that the linefeed is also desirable and appropriate under Windows, I added + '\n' within hook.py thusly to get it working as I'd expect on my system:

def init_excepthook(color):
    def excepthook(exc_type, exc_value, traceback):
        tb_str = formatting.exc_to_traceback_str(exc_value, traceback, color) + '\n'

AssertionError module.endswith

Executing python file as python script.py works fine. But if I try to do python ./script.py it gives the following error

Error in sys.excepthook:
Traceback (most recent call last):
  File "C:\Users\M1\anaconda3\envs\myenv\lib\site-packages\pretty_traceback\hook.py", line 23, in excepthook
    tb_str = formatting.exc_to_traceback_str(exc_value, traceback, color)
  File "C:\Users\M1\anaconda3\envs\myenv\lib\site-packages\pretty_traceback\formatting.py", line 281, in exc_to_traceback_str
    return format_tracebacks(tracebacks, color)
  File "C:\Users\M1\anaconda3\envs\myenv\lib\site-packages\pretty_traceback\formatting.py", line 255, in format_tracebacks
    traceback_str = format_traceback(tb_tup, color)
  File "C:\Users\M1\anaconda3\envs\myenv\lib\site-packages\pretty_traceback\formatting.py", line 244, in format_traceback
    ctx = _init_entries_context(traceback.entries)
  File "C:\Users\M1\anaconda3\envs\myenv\lib\site-packages\pretty_traceback\formatting.py", line 156, in _init_entries_context
    rows = list(_iter_entry_rows(aliases, entry_paths, entries))
  File "C:\Users\M1\anaconda3\envs\myenv\lib\site-packages\pretty_traceback\formatting.py", line 135, in _iter_entry_rows
    assert module.endswith(_module)
AssertionError

Should it work in any terminal? It doesn't seem to work in my case

Tried to see pretty-tracebak in action in some of my scripts, doesn't seem to work.
Doing import and install() in entry points of my scripts. It imports the module, but traceback stays the same

Done the same thing in Python shell, just to show the screenshot here
Should it work in Python shell btw?

Screenshot from 2024-01-05 14-18-48

TERM colours and different output.

I might be doing something wrong but this is what I see:

screenshot

The script:

#!/usr/bin/env python3
"""CRASH!"""

#import stackprinter
#stackprinter.set_excepthook(style='darkbg2')  # for jupyter notebooks try style='lightbg'

try:
    import pretty_traceback
    #pretty_traceback.install(envvar='ENABLE_PRETTY_TRACEBACK')
    pretty_traceback.install()
except ImportError:
    pass    # no need to fail because of missing dev dependency


def main():
    1 / 0


if __name__ == "__main__":
    main()

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.