Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reduce Python's Exception raising output?

I have this line of Python code:

raise ValueError(f"Invalid input '{number}'")

When it raises an exception I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/snowcrash/Code/Python/mycode/mycode.py", line 8, in __init__
    raise ValueError(f"Invalid input '{number}'")
ValueError: Invalid input 'a1b2c3'

however I'd prefer to get:

File "/home/snowcrash/Code/Python/mycode/mycode.py", line 8, in __init__
  ValueError: Invalid input 'a1b2c3'

How do I achieve this?

like image 511
Snowcrash Avatar asked Dec 14 '25 14:12

Snowcrash


1 Answers

sys.excepthook(type, value, traceback) is the function that does the printing when an exception is raised. You can write your own function (with a similar signature) and simply replace it with:

sys.excepthook = myfunction

You can do whatever you want in this function. You may log to files, or print some information about the state of the program when the exception occurred, for example. You may even arrange for different things to happen depending on the type of exception.

However if all you want to do is format your traceback message, lots of convenient stuff is already provided for you. You can dig into the traceback docs for the details, but here is an example that produces roughly the output you want:

import sys, traceback


def myhook(type, value, tb):
    trace = traceback.format_tb(tb, limit=1)
    trace = trace[0].split("\n")[0]
    exc = traceback.format_exception_only(type, value)[0]
    print(trace + "\n" + exc)


sys.excepthook = myhook

number = "a1b2c3"
raise ValueError(f"Invalid input {number}")

which produces an output of:

  File "scratch/so.py", line 14, in <module>
ValueError: Invalid input a1b2c3

Note especially the use of traceback.format_tb with limit=1, to limit the stack trace output. There are a bunch of these functions in the traceback module.

like image 105
L.Grozinger Avatar answered Dec 16 '25 23:12

L.Grozinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!