gpt4 book ai didi

python - 打印错误消息而不打印回溯,并在不满足条件时关闭程序

转载 作者:太空狗 更新时间:2023-10-29 17:08:58 25 4
gpt4 key购买 nike

我见过与此类似的问题,但没有一个真正解决引用通告问题。如果我有这样的类(class)

class Stop_if_no_then():
def __init__(self, value one, operator, value_two, then, line_or_label, line_number):
self._firstvalue = value_one
self._secondvalue = value_two
self._operator = operator
self._gohere = line_or_label
self._then = then
self._line_number = line_number

def execute(self, OtherClass):
"code comparing the first two values and making changes etc"

我希望我的执行方法能够做的是,如果 self._then 不等于字符串“THEN”(全部大写),那么我希望它引发自定义错误消息并终止整个程序,同时也不显示回溯。

如果遇到错误,唯一应该打印出来的东西看起来像这样(我以 3 为例,格式化不是问题)。

`Syntax Error (Line 3): No -THEN- present in the statement.`

我对它实际上是一个异常类对象不是很挑剔,所以在这方面没有问题。因为我将在 while 循环中使用它,简单的 if,elif 只是一遍又一遍地重复消息(因为显然我没有关闭循环)。我见过 sys.exit() 但它也会打印出一大块红色文本,除非我没有正确使用它。我不想在我的循环中捕获异常,因为同一个模块中还有其他类,我需要在其中实现类似的东西。

最佳答案

您可以通过限制其深度来关闭回溯。

python 2.x

import sys
sys.tracebacklimit = 0

python 3.x

在 Python 3.5.2 和 3.6.1 中,设置 tracebacklimit0 似乎没有预期的效果。这是一个已知的 bug .请注意,-1 也不起作用。然而,将其设置为 None 似乎确实有效,至少目前是这样。

在 Python 3.6.2 及更高版本中,您应该将 tracebacklimit 设置为 0-1,将其设置为 None 不会禁用回溯输出。

Python 3.6.1 和以下结果:

>>> import sys

>>> sys.tracebacklimit = 0
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception

>>> sys.tracebacklimit = -1
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception

>>> sys.tracebacklimit = None
>>> raise Exception
Exception

Python 3.6.2 及以上结果:

>>> import sys

>>> sys.tracebacklimit = 0
>>> raise Exception
Exception

>>> sys.tracebacklimit = -1
>>> raise Exception
Exception

>>> sys.tracebacklimit = None
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception

然而,无论好坏,如果出现多个异常,它们仍然可以全部打印出来。例如:

socket.gaierror: [Errno -2] Name or service not known

During handling of the above exception, another exception occurred:

urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>

关于python - 打印错误消息而不打印回溯,并在不满足条件时关闭程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784849/

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