仅显示追溯的第一行和最后一行

The*_*ius 2 python dsl

我已经用python构建了一些内部DSL。我正在使用assertvor验证。如果最终用户键入了错误的参数,则dsl应该报告错误之处。此刻看起来像这样:

Traceback (most recent call last):
  File "tests/maskedtimefilter_test/FilterDSL_test.py", line 63, in test_dsl_validation
    input(0): self.regular
  File "/Users/sh/reetz/pythonpath/maskedtimedata/maskedtimefilter.py", line 885, in __lshift__
    kwargs = self.dsl_validation(kwargs)
  File "/Users/sh/reetz/pythonpath/maskedtimedata/maskedtimefilter.py", line 1483, in dsl_validation
    check_if_valid(parameter)
  File "/Users/sh/reetz/pythonpath/maskedtimedata/dsl.py", line 47, in kernel_a
    def kernel_a (x): assert isinstance(x, (list, tuple, np.ndarray)), "kernel must be a list."
AssertionError: kernel must be a list.
Run Code Online (Sandbox Code Playgroud)

但是最终用户是工程师,而不是计算机科学家。因此,使用最小的Traceback很方便。是否可以像这样将Traceback缩小到基本信息(故障在哪里,是什么原因)?:

Traceback (most recent call last):
  File "tests/maskedtimefilter_test/FilterDSL_test.py", line 63, in test_dsl_validation
    input(0): self.regular
AssertionError: kernel must be a list.
Run Code Online (Sandbox Code Playgroud)

我很不情愿地使用普通的照片!

Lor*_*ill 6

为什么不将回溯数据作为数组返回并从中进行回算呢?

import traceback
try:
     codethatwillthrowanexception()
except:
     exceptiondata = traceback.format_exc().splitlines()
     exceptionarray = [exceptiondata[-1]] + exceptiondata[1:-1]
Run Code Online (Sandbox Code Playgroud)


roi*_*ppi 5

您可以在调用堆栈中的某个位置执行以下操作:

try:
    my_function_that_can_raise_exception()
except Exception: #or AssertionError
    import traceback
    traceback.print_exc(limit=1)
Run Code Online (Sandbox Code Playgroud)

limit是您要显示的堆栈跟踪条目的深度。(在你的情况下,1)

演示:

In [21]: def f():
    ...:     assert False == True, 'Assertion!'
    ...:     

In [22]: try:
    ...:     f()
    ...: except Exception:
    ...:     import traceback
    ...:     traceback.print_exc(limit=1)
    ...:     
Traceback (most recent call last):
  File "<ipython-input-22-78f9db8d5188>", line 2, in <module>
    f()
AssertionError: Assertion!
Run Code Online (Sandbox Code Playgroud)

tracebackdocs阅读更多内容。