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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17784849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:12:14  来源:igfitidea点击:

Print an error message without printing a traceback and close the program when a condition is not met

pythonexceptionerror-handlingcustomizationtraceback

提问by user2560035

I've seen similar questions to this one but none of them really address the trackback. If I have a class like so

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

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"

What I want my execute method to be able to do is if self._then is not equal to the string "THEN" (in allcaps) then I want it to raise a custom error message and terminate the whole program while also not showing a traceback.

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

If the error is encountered the only thing that should print out would look something like (I'm using 3 as an example, formatting is not a problem) this.

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

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

I'm not very picky about it actually being an exception class object, so there's no issue in that aspect. Since I will be using this in a while loop, simple if, elif just repeats the message over and over (because obviously I am not closing the loop). I have seen sys.exit() but that also prints out a giant block of red text, unless I am not using it correctly. I don't want to catch the exception in my loop because there are other classes in the same module in which I need to implement something like this.

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

采纳答案by The-IT

You can use a try:and then except Exception as inst:What that will do is give you your error message in a variable named inst and you can print out the arguments on the error with inst.args. Try printing it out and seeing what happens, and is any item in inst.argsis the one you are looking for.

您可以使用 atry:然后except Exception as inst:这样做会在名为 inst 的变量中为您提供错误消息,您可以使用inst.args. 尝试将其打印出来,看看会发生什么,并且其中的任何项目inst.args都是您要查找的项目。

EDIT Here is an example I tried with pythons IDLE:

编辑这是我用pythons IDLE试过的一个例子:

>>> try:
    open("epik.sjj")
except Exception as inst:
    d = inst


>>> d
FileNotFoundError(2, 'No such file or directory')
>>> d.args
(2, 'No such file or directory')
>>> d.args[1]
'No such file or directory'
>>> 

EDIT 2: as for closing the program you can always raiseand error or you can use sys.exit()

编辑 2:至于关闭程序,您可以随时raise出错,或者您可以使用sys.exit()

回答by Marco Costa

You can turn off the traceback by limiting its depth.

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

Python 2.x

蟒蛇 2.x

import sys
sys.tracebacklimit = 0

Python 3.x

蟒蛇 3.x

In Python 3.5.2 and 3.6.1, setting tracebacklimitto 0does not seem to have the intended effect. This is a known bug. Note that -1doesn't work either. Setting it to Nonedoes however seem to work, at least for now.

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

>>> 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

Nevertheless, for better or worse, if multiple exceptions are raised, they can all still be printed. For example:

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

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>

回答by Acumenus

In general, if you want to catch any exception except SystemExit, and exit with the exception's message without the traceback, define your mainfunction as below:

通常,如果您想捕获任何异常 except SystemExit,并在没有回溯的情况下以异常消息退出,请main按如下方式定义您的函数:

>>> import sys

>>> def main():
...     try:
...         # Run your program from here.
...         raise RandomException  # For testing
...     except (Exception, KeyboardInterrupt) as exc:
...         sys.exit(exc)
... 
>>> main()
name 'RandomException' is not defined

$ echo $?
1

Note that in the case of multiple exceptions being raised, only one message is printed.

请注意,在引发多个异常的情况下,只会打印一条消息。

This answer is meant to improve upon the one by The-IT.

该答案旨在改进The-IT 的答案。

回答by creuilcreuil

If you want to get rid of any traceback for customs exceptions and have line number, you can do this trick

如果你想摆脱海关例外的任何追溯并有行号,你可以这样做

Python 3

蟒蛇 3

import sys
import inspect

class NoTraceBackWithLineNumber(Exception):
    def __init__(self, msg):
        try:
            ln = sys.exc_info()[-1].tb_lineno
        except AttributeError:
            ln = inspect.currentframe().f_back.f_lineno
        self.args = "{0.__name__} (line {1}): {2}".format(type(self), ln, msg),
        sys.exit(self)

class MyNewError(NoTraceBackWithLineNumber):
    pass

raise MyNewError("Now TraceBack Is Gone")

Will give this output, and make the raisekeyword useless

将给出此输出,并使raise关键字无用

MyNewError (line 16): Now TraceBack Is Gone

回答by Mark Veltzer

The cleanest way that I know is to use sys.excepthook.

我所知道的最干净的方法是使用sys.excepthook.

You implement a three argument function that accepts type, value, and tracebackand does whatever you like (say, only prints the value) and assign that function to sys.excepthook.

您实现了一个三参数函数,该函数接受typevaluetraceback并执行您喜欢的任何操作(例如,仅打印值)并将该函数分配给sys.excepthook

Here is an example:

下面是一个例子:

import sys

def excepthook(type, value, traceback):
    print(value)

sys.excepthook = excepthook

raise ValueError('hello')

This is available in both python 2 and python 3.

这在 python 2 和 python 3 中都可用。

回答by user3487934

You can use SystemExit exception:

您可以使用 SystemExit 异常:

except Exception as err:
    raise SystemExit(err)

https://docs.python.org/3/library/exceptions.html

https://docs.python.org/3/library/exceptions.html