Python回溯,如何隐藏绝对路径?

oru*_*dyy 4 python exception traceback python-3.8

我想知道是否有一种简单的方法可以防止Python回溯在出现错误时打印文件的完整路径。例如,下面的回溯打印生成异常的文件的绝对路径:

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

我希望它只打印相对路径:project_align/src/main.py

是否有某个配置参数可以强制执行此操作?

abh*_*jat 8

我不知道是否有一个标志可以执行此操作,但如果您确实愿意,您可以使用自己的函数覆盖 sys.excepthook,在其中您可以创建 TracebackException,从帧摘要中删除所有文件名,并格式化和打印它。

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()
Run Code Online (Sandbox Code Playgroud)

输出是

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
Run Code Online (Sandbox Code Playgroud)

原始输出是

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
Run Code Online (Sandbox Code Playgroud)