gpt4 book ai didi

python 3 : Don't show full directory path on error message

转载 作者:太空狗 更新时间:2023-10-30 00:06:01 25 4
gpt4 key购买 nike

有没有办法在执行python程序时只显示重要的目录路径?

目前我得到这个:

python3 foo.py                                        
Traceback (most recent call last):
File "foo.py", line 60, in <module>
foo = Foo()
File "foo.py", line 22, in __init__
self._run()
File "/media/MyDocuments/xxxxxxx/yyyyyyyyy/python_code/foo.py", line 18, in check_input
bar = obj.get_action()
AttributeError: 'obj' object has no attribute 'get_action'

据我所知,我的代码在哪个目录中,完整的目录使错误消息的可读性更差。我可以告诉 python 向我显示更像这样的输出吗?

python3 foo.py                                        
Traceback (most recent call last):
File "foo.py", line 60, in <module>
foo = Foo()
File "foo.py", line 22, in __init__
self._run()
File ".../foo.py", line 18, in check_input
bar = obj.get_action()
AttributeError: 'obj' object has no attribute 'get_action'

回答

使用 unutbu 中的代码,我添加了一些颜色行,如果有人正在寻找对解释器输出的简单改进,只需将其用作模块并导入它:

import sys
import traceback
import os
import re

RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
END = '\033[0m'

def my_excepthook(type, value, tb):
lines = traceback.format_list(traceback.extract_tb(tb))
def shorten(match):
return 'File "{}"'.format(os.path.basename(match.group(1)))
lines = [re.sub(r'File "([^"]+)"', shorten, line) for line in lines]
_print_color(lines)
# print(''.join(lines))
print(RED + '{}: {}'.format(type.__name__, value) + END)

sys.excepthook = my_excepthook


def _print_color(lines):
for l in lines:
for i in range(len(l)-1):
if l[i:i+5]=="line ":
i +=5
# Find the length of the number
numLen = 0
while l[i+numLen].isdigit():
numLen +=1

# Find the length of the function
funLen = 0
while not l[i+numLen+4 + funLen]=="\n":
funLen+=1

l = ''.join([l[:i],
YELLOW+"{}".format(l[i:i+numLen])+END,
l[i+numLen:i+numLen+5],
LIGHT_PURPLE+"{}".format(l[i+numLen+5:i+numLen+5+funLen])+END,
CYAN+"{}".format(l[i+numLen+5+funLen:])+END])
print(l,end="")
break
print("")

最佳答案

您可以将自定义函数分配给 sys.excepthookhandle all uncaught exceptions :

sys.excepthook = my_excepthook

然后你可以使用

def my_excepthook(type, value, tb):
lines = traceback.format_list(traceback.extract_tb(tb))
# process/modify lines
print(''.join(lines))

以一系列行的形式获取回溯错误消息,然后根据需要进行修改和打印。


例如,如果您希望将所有文件路径缩短为其基本名称,您可以使用:

import sys
import traceback
import os
import re

def my_excepthook(type, value, tb):
lines = traceback.format_list(traceback.extract_tb(tb))
def shorten(match):
return 'File "{}"'.format(os.path.basename(match.group(1)))
lines = [re.sub(r'File "([^"]+)"', shorten, line, 1) for line in lines]
print(''.join(lines))
print('{}: {}'.format(type.__name__, value))

sys.excepthook = my_excepthook # comment this out to see the difference

class Foo():
def run(self):
1/0

foo = Foo()
foo.run()

产生

  File "script.py", line 24, in <module>
foo.run()
File "script.py", line 21, in run
1/0

ZeroDivisionError: division by zero

代替

Traceback (most recent call last):
File "/home/unutbu/pybin/script.py", line 24, in <module>
foo.run()
File "/home/unutbu/pybin/script.py", line 21, in run
1/0
ZeroDivisionError: division by zero

关于 python 3 : Don't show full directory path on error message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37056981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com