typer
typer copied to clipboard
[QUESTION] How do I disable typer's exception handler
I want to be able to disable typer/Click's exception handler, and handle the exceptions myself. I see that in click you can do this by setting standalone_mode = False in the command.main() function.
to answer my own question after some digging it looks like you can do this....
if you normally have
import typer
app = typer.Typer()
if __name__ == '__main__':
app()
you can instead do
import typer
app = typer.Typer()
if __name__ == '__main__':
command = typer.main.get_command(app)
try:
result = command(standalone_mode=False)
except:
print(f'exception was thrown')
sys.exit(result)
I dug into the source code and found that typer.run
is simply a wrapper for
app = typer.Typer()
app.command()(main)
app()` # <-- this app takes the standalone_mode argurment
I saw this question when I was looking at disabling the typer's exception message in case of issue, as it was too verbose. It's not really related to this question, but could be useful for others. What I needed to do was to disable the prettier_exceptions, which in my case only show_locals was the issue:
app = typer.Typer(add_completion=False, pretty_exceptions_show_locals = False)
or to remove the typer exception completely:
app = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
A disadvantage of setting standalone_mode=False
is that exceptions from Click like click.UsageError
won't be handled by Typer anymore. Since _original_except_hook
is set when importing Typer, and is called by Typer when pretty_exceptions_enable=False
, a (rather ugly) workaround is to set sys.excepthook
before importing Typer.
I actually preferd to add a handler for the throws, then I still benefit from more of typer
's goodness:
try:
app()
except SystemExit as ex:
if ex.args[0] != 0:
raise
# else continue, all is well
[Maintenance note]: moving this to the discussion forum - we can continue the discussion there! 🙏