Python tracebacks, how to hide absolute paths?
Asked Answered
S

1

6

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?

Stannic answered 11/11, 2021 at 8:26 Comment(0)
L
11

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
Luo answered 11/11, 2021 at 9:7 Comment(1)
I wish traceback module had some parameter for this, but your solution does the work. Thanks!Stannic

© 2022 - 2024 — McMap. All rights reserved.