Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tracebacks, how to hide absolute paths?

I would like to know if there is an easy way to prevent Python tracebacks to print the full path of files when there is an error. For example, the traceback below prints the absolute path of the file generating the exception:

Traceback (most recent call last):
  File "C:/Users/user/Documents/project/project_align/src/main.py", line 62, in <module>
    raise Exception
Exception

I wish it to just print the relative path instead: project_align/src/main.py

Is there a configuration parameter somewhere to force this?

like image 309
orudyy Avatar asked Sep 01 '26 19:09

orudyy


1 Answers

I do not know if there is a flag to do this, but if you really want to, you can override sys.excepthook with your own function, within which you can create a TracebackException, remove all filenames from the frame summaries, and format and print it.

import os
import sys
import traceback


def handler(_exception_type, _value, t):
    exc = traceback.TracebackException(_exception_type, _value, t)

    # replace file names for each frame summary
    for frame_summary in exc.stack:
        frame_summary.filename = os.path.relpath(frame_summary.filename)

    # format and print the exception
    print(''.join(exc.format()), file=sys.stderr)


sys.excepthook = handler


def crashes_hard():
    print(1 / 0)


def crashes():
    crashes_hard()


crashes()

The output is

Traceback (most recent call last):
  File "scratch_1.py", line 31, in <module>
    crashes()
  File "scratch_1.py", line 28, in crashes
    crashes_hard()
  File "scratch_1.py", line 24, in crashes_hard
    print(1 / 0)
ZeroDivisionError: division by zero

The original output is

Traceback (most recent call last):
  File "/home/abhijat/.config/.../scratches/scratch_1.py", line 31, in <module>
    crashes()
  File "/home/abhijat/.config/.../scratches/scratch_1.py", line 28, in crashes
    crashes_hard()
  File "/home/abhijat/.config/.../scratches/scratch_1.py", line 24, in crashes_hard
    print(1 / 0)
ZeroDivisionError: division by zero
like image 90
abhijat Avatar answered Sep 04 '26 10:09

abhijat



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!