{"id":13501588,"url":"https://github.com/cknd/stackprinter","last_synced_at":"2025-05-14T11:10:54.855Z","repository":{"id":33962459,"uuid":"147504167","full_name":"cknd/stackprinter","owner":"cknd","description":"Debugging-friendly exceptions for Python","archived":false,"fork":false,"pushed_at":"2024-03-13T20:07:59.000Z","size":1565,"stargazers_count":1288,"open_issues_count":11,"forks_count":37,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-04-11T04:55:42.327Z","etag":null,"topics":["debugging","error-logging","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cknd.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-09-05T10:58:47.000Z","updated_at":"2025-04-09T09:45:52.000Z","dependencies_parsed_at":"2024-06-18T13:33:49.600Z","dependency_job_id":"d06956e3-04d7-4981-a8ed-be182fda6ea0","html_url":"https://github.com/cknd/stackprinter","commit_stats":{"total_commits":182,"total_committers":9,"mean_commits":20.22222222222222,"dds":0.1208791208791209,"last_synced_commit":"3fec578c9edd6f4c368eed7821c5825017951695"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cknd%2Fstackprinter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cknd%2Fstackprinter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cknd%2Fstackprinter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cknd%2Fstackprinter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cknd","download_url":"https://codeload.github.com/cknd/stackprinter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253837387,"owners_count":21971981,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["debugging","error-logging","python"],"created_at":"2024-07-31T22:01:42.566Z","updated_at":"2025-05-14T11:10:54.777Z","avatar_url":"https://github.com/cknd.png","language":"Python","readme":"\u003cimg src=\"https://raw.githubusercontent.com/cknd/stackprinter/master/darkbg.png\" width=\"500\"\u003e\n\n[![build](https://github.com/cknd/stackprinter/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/cknd/stackprinter/actions/workflows/build.yml)\n\n# Better tracebacks\n\nThis is a more helpful version of Python's built-in exception message: It shows more code context and the current values of nearby variables. That answers many of the questions I'd ask an interactive debugger: Where in the code was the crash, what's in the relevant variables, and why was _that_ function called with _those_ arguments. It either prints to the console or gives you a string for logging.\n\n```bash\npip3 install stackprinter\n```\n### Before\n```\nTraceback (most recent call last):\n  File \"demo.py\", line 12, in \u003cmodule\u003e\n    dangerous_function(somelist + anotherlist)\n  File \"demo.py\", line 6, in dangerous_function\n    return sorted(blub, key=lambda xs: sum(xs))\n  File \"demo.py\", line 6, in \u003clambda\u003e\n    return sorted(blub, key=lambda xs: sum(xs))\nTypeError: unsupported operand type(s) for +: 'int' and 'str'\n```\n\n### After\n```\nFile demo.py, line 12, in \u003cmodule\u003e\n    9        somelist = [[1,2], [3,4]]\n    10       anotherlist = [['5', 6]]\n    11       spam = numpy.zeros((3,3))\n--\u003e 12       dangerous_function(somelist + anotherlist)\n    13   except:\n    ..................................................\n     somelist = [[1, 2, ], [3, 4, ], ]\n     anotherlist = [['5', 6, ], ]\n     spam = 3x3 array([[0. 0. 0.]\n                       [0. 0. 0.]\n                       [0. 0. 0.]])\n    ..................................................\n\nFile demo.py, line 6, in dangerous_function\n    5    def dangerous_function(blub):\n--\u003e 6        return sorted(blub, key=lambda xs: sum(xs))\n    ..................................................\n     blub = [[1, 2, ], [3, 4, ], ['5', 6, ], ]\n    ..................................................\n\nFile demo.py, line 6, in \u003clambda\u003e\n    3\n    4\n    5    def dangerous_function(blub):\n--\u003e 6        return sorted(blub, key=lambda xs: sum(xs))\n    7\n    ..................................................\n     xs = ['5', 6, ]\n    ..................................................\n\nTypeError: unsupported operand type(s) for +: 'int' and 'str'\n```\nI rarely use this locally instead of a real debugger, but it helps me sleep when my code runs somewhere where the only debug tool is a log file (though it's not a fully-grown [error monitoring system](https://sentry.io/welcome/)).\n\nBy default, it tries to be somewhat polite about screen space, showing only a few source lines \u0026 the function header, and only the variables _that appear in those lines_, and using only (?) 500 characters per variable. You can [configure](https://github.com/cknd/stackprinter/blob/master/stackprinter/__init__.py#L28-L149) exactly how verbose things should be.\n\nIt outputs plain text normally, which is good for log files. There's also a color mode for some reason 🌈, with a few different color schemes for light and dark backgrounds. (The colors [track different variables](https://medium.com/@brianwill/making-semantic-highlighting-useful-9aeac92411df) instead of the language syntax.)\n\n\u003cimg src=\"https://raw.githubusercontent.com/cknd/stackprinter/master/notebook.png\" width=\"500\"\u003e\n\n# Usage\n\n## Option 1: Set and forget\nTo replace the default python crash printout, call `set_excepthook()` somewhere once. Afterwards, any uncaught exception will be printed with an extended traceback (to stderr, by default). You could also [make this permanent for your python installation](#making-it-stick).\n\n```python\nimport stackprinter\nstackprinter.set_excepthook(style='darkbg2')  # for jupyter notebooks try style='lightbg'\n```\n## Option 2: Call it selectively during exception handling\nFor more control, call [`show()`](https://github.com/cknd/stackprinter/blob/master/stackprinter/__init__.py#L166-L183) or [`format()`](https://github.com/cknd/stackprinter/blob/master/stackprinter/__init__.py#L28-L149) inside an `except` block. `show()` prints to stderr, `format()` returns a string, for custom logging.\n\n```python\ntry:\n    something()\nexcept:\n    # print the current exception to stderr:\n    stackprinter.show()\n\n    # ...or instead, get a string for logging:\n    logger.error(stackprinter.format())\n```\nOr pass specific exceptions explicitly:\n```python\ntry:\n    something()\nexcept RuntimeError as exc:\n    tb = stackprinter.format(exc)\n    logger.error('The front fell off.\\n' + tb)\n```\n\n## Config options\n\n`format()`, `show()` and `set_excepthook()` accept a common set of keyword args. They allow you to tweak the formatting, hide certain variables by name, skip variables in calls within certain files, and some other stuff. \n\n```python\ntry:\n    something()\nexcept RuntimeError as exc:\n    stackprinter.show(exc, suppressed_vars=[r\".*secret.*\"],\n                           suppressed_paths=[r\"lib/python.*/site-packages/boringstuff\"],\n                           truncate_vals=9001,\n                           style=\"darkbg2\")\n```\nFor all the options [see the docstring of `format()`](https://github.com/cknd/stackprinter/blob/master/stackprinter/__init__.py#L28-L149).\n\n## Option 3: Integrate with the standard `logging` module\n\nWith a bit of extra plumbing you can log errors like this via the normal `logging` methods, without having to import `stackprinter` at the site of the logging call. So you can continue to write nice and simple error handlers like so...\n\n```python\nlogger = logging.getLogger()\ntry:\n    nothing = {}\n    dangerous_function(nothing.get(\"something\"))\nexcept:\n    logger.exception('My hovercraft is full of eels.')\n```\n...but still get annotated tracebacks in the resulting log.\n```\n2022-04-02 16:16:40,905 ERROR: My hovercraft is full of eels.\n  ┆ File \"demo_logging.py\", line 56, in \u003cmodule\u003e\n  ┆     54   try:\n  ┆     55       nothing = {}\n  ┆ --\u003e 56       dangerous_function(nothing.get(\"something\"))\n  ┆     57   except:\n  ┆     ..................................................\n  ┆      nothing = {}\n  ┆     ..................................................\n  ┆\n  ┆ File \"demo_logging.py\", line 52, in dangerous_function\n  ┆     51   def dangerous_function(something):\n  ┆ --\u003e 52       return something + 1\n  ┆     ..................................................\n  ┆      something = None\n  ┆     ..................................................\n  ┆\n  ┆ TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'\n```\n\nYou can get this by adding a [custom formatter](https://docs.python.org/3/howto/logging-cookbook.html#customized-exception-formatting) to the logger before using it:\n\n```python\nimport logging\nimport stackprinter\n\nclass VerboseExceptionFormatter(logging.Formatter):\n    def formatException(self, exc_info):\n        msg = stackprinter.format(exc_info)\n        lines = msg.split('\\n')\n        lines_indented = [\"  ┆ \" + line + \"\\n\" for line in lines]\n        msg_indented = \"\".join(lines_indented)\n        return msg_indented\n\ndef configure_logger(logger_name=None):\n    fmt = '%(asctime)s %(levelname)s: %(message)s'\n    formatter = VerboseExceptionFormatter(fmt)\n\n    handler = logging.StreamHandler()\n    handler.setFormatter(formatter)\n\n    logger = logging.getLogger(logger_name)\n    logger.addHandler(handler)\n\nconfigure_logger(\"some_logger\")\n```\nSee [demo_logging.py](https://github.com/cknd/stackprinter/blob/master/demo_logging.py) for a runnable example.\n\n## Printing the current call stack\nTo see your own thread's current call stack, call `show` or `format` anywhere outside of exception handling.\n\n```python\nstackprinter.show() # or format()\n```\n\n## Printing the stack of another thread\nTo inspect the call stack of any other running thread:\n\n```python\nthread = threading.Thread(target=something)\nthread.start()\n# (...)\nstackprinter.show(thread) # or format(thread)\n```\n\n## Making it stick\n\nTo permanently replace the crash message for your python installation, you *could* put a file `sitecustomize.py` into the `site-packages` directory under one of the paths revealed by `python -c \"import site; print(site.PREFIXES)\"`, with contents like this:\n\n```python\n    # in e.g. some_virtualenv/lib/python3.x/site-packages/sitecustomize.py:\n    import stackprinter\n    stackprinter.set_excepthook(style='darkbg2')\n```\n\nThat would give you colorful tracebacks automatically every time, even in the REPL.\n\n(You could do a similar thing for IPython, [but they have their own method](https://ipython.readthedocs.io/en/stable/interactive/tutorial.html?highlight=startup#configuration), where the file goes into `~/.ipython/profile_default/startup` instead, and also I don't want to talk about what this module does to set an excepthook under IPython.)\n\n# Docs\n\nFor now, the documentation consists only of some fairly detailed docstrings, [e.g. those of `format()`](https://github.com/cknd/stackprinter/blob/master/stackprinter/__init__.py#L28-L149)\n\n# Caveats\n\nThis displays variable values as they are _at the time of formatting_. In\nmulti-threaded programs, variables can change while we're busy walking\nthe stack \u0026 printing them. So, if nothing seems to make sense, consider that\nyour exception and the traceback messages are from slightly different times.\nSadly, there is no responsible way to freeze all other threads as soon\nas we want to inspect some thread's call stack (...or is there?)\n\n# How it works\n\nBasically, this is a frame formatter. For each [frame on the call stack](https://en.wikipedia.org/wiki/Call_stack), it grabs the source code to find out which source lines reference which variables. Then it displays code and variables in the neighbourhood of the last executed line.\n\nSince this already requires a map of where each variable occurs in the code, it was difficult not to also implement the whole semantic highlighting color thing seen in the screenshots. The colors are ANSI escape codes now, but it should be fairly straightforward™ to render the underlying data without any 1980ies terminal technology. Say, a foldable and clickable HTML page with downloadable pickled variables. For now you'll have to pipe the ANSI strings through [ansi2html](https://github.com/ralphbean/ansi2html/) or something.\n\nThe format and everything is inspired by the excellent [`ultratb`](https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.ultratb.html) in IPython. One day I'd like to contribute the whole \"find out which variables in `locals` and `globals` are nearby in the source and print only those\" machine over there, after trimming its complexity a bit.\n\n## Tracing a piece of code\n\nMore for curiosity than anything else, you can watch a piece of code execute step-by-step, printing a trace of all calls \u0026 returns 'live' as they are happening. Slows everything down though, of course.\n```python\nwith stackprinter.TracePrinter(style='darkbg2'):\n    dosomething()\n```\n\nor\n```python\ntp = stackprinter.TracePrinter(style='darkbg2')\ntp.enable()\ndosomething()\n# (...) +1 million lines\ntp.disable()\n```\n\u003cimg src=\"https://raw.githubusercontent.com/cknd/stackprinter/master/trace.png\" width=\"300\"\u003e\n\n","funding_links":[],"categories":["Python","Logging","Error Monitoring Tools"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcknd%2Fstackprinter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcknd%2Fstackprinter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcknd%2Fstackprinter/lists"}