fastapi / typer

Typer, build great CLIs. Easy to code. Based on Python type hints.

Home Page:https://typer.tiangolo.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

It is difficult to add a sys.excepthook without typer replacing and ignoring it

damonmaria opened this issue · comments

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the Typer documentation, with the integrated search.
  • I already searched in Google "How to X in Typer" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to Typer but to Click.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

import sys
import os
from typer import run


def main():
    raise RuntimeError()


def hook_example(*_):
    orig_hook(*_)
    print("Hook called")


orig_hook = sys.excepthook
sys.excepthook = hook_example
os.environ["_TYPER_STANDARD_TRACEBACK"] = "true"
if __name__ == '__main__':
    run(main)

Description

  • I am trying to have my own sys.excepthook override, not typer's one
  • The example code posted does not fire hook_example()
  • The way typer sets up it's own excepthook makes this difficult, the only way to make it work is to ensure you have replaced sys.excepthook before typer is imported which is difficult not get right and a difficult to not break when refactoring
  • The reason is typer stores _original_except_hook = sys.excepthook at it's top level in main.py but does not replace sys.excepthook until it's actually called
  • IMHO what should happen instead:
    • typer should store the original hook at the time it replaces it
    • There should be a programatic way to disable typer's excepthook override (not just through an env var)
  • I am happy to do the PR for this

Operating System

Linux, macOS

Operating System Details

No response

Typer Version

0.6.1

Python Version

3.8.13

Additional Context

No response

I agree with you.

This may help? #129 (comment)

I encountered the same issue too.
I suggest as a solution to be saving _original_except_hook just when calling the typer, and not when importing it.
What do you think? Can I open a PR to solve it?