我刚刚写了辅助函数ExcText(),你可以看看我是如何在test()函数中使用它的。如果您将其称为ExcText(False),则不会打印代码行,如果将其称为ExcText(True),则会打印它们。
Try it online!
def ExcText(show_lines):
import sys, traceback
r = traceback.StackSummary.extract(traceback.walk_tb(sys.exc_info()[2]))
if not show_lines:
for i, e in enumerate(r):
r[i]._line = ''
return ''.join(['Traceback (most recent call last):\n'] + r.format() +
traceback.format_exception_only(*sys.exc_info()[:2]))
def test():
try:
def g():
assert False, 'Hello, World!'
def f():
g()
f()
except:
print(ExcText(False))
test()
ExcText(False) 的输出:
Traceback (most recent call last):
File "C:\t\test.py", line 16, in test
File "C:\t\test.py", line 15, in f
File "C:\t\test.py", line 13, in g
AssertionError: Hello, World!
ExcText(True) 的输出:
Traceback (most recent call last):
File "C:\t\test.py", line 16, in test
f()
File "C:\t\test.py", line 15, in f
g()
File "C:\t\test.py", line 13, in g
assert False, 'Hello, World!'
AssertionError: Hello, World!
您也可以使用上面的代码来捕获语法错误,只需执行compile(program_text, '<string>', 'exec'),其中程序文本是包含需要检查的脚本文本的字符串,例如code is here。您还可以通过以下方式从文件中读取程序文本:
with open(filename, 'r', encoding = 'utf-8') as f:
prog = f.read()
当你只需要语法检查时,你应该使用compile()而不是exec(),因为脚本(程序文本)可能包含一些恶意代码(如木马),exec()会在检查语法后执行它,而@987654339 @ 不会执行,只是检查它是否可编译并且没有语法错误。
也可以通过修改linecache.getline()函数来实现代码行的不打印,如下所示。
但请注意,此解决方案会修改标准模块,因此应尽可能避免这种 hack。上面的第一个解决方案更好。
Try it online!
def test():
import traceback
traceback.linecache.getline = lambda *pargs, **nargs: ''
try:
def g():
assert False, 'Hello, World!'
def f():
g()
f()
except:
traceback.print_exc()
test()
输出:
Traceback (most recent call last):
File "C:\t\test.py", line 10, in test
File "C:\t\test.py", line 9, in f
File "C:\t\test.py", line 7, in g
AssertionError: Hello, World!