在不退出程序的情况下引发异常

时间:2020-07-07 18:51:44

标签: python python-3.x python-3.7 nameerror raiseerror

我在Windows上使用python 3.7.7。我正在尝试打高尔夫球。在那e。如果您引发异常(请明确NameError),如下所示:

raise NameError("Your input was not recognized as a function, variable or  datatype")

然后程序自动退出。 当我尝试这样做时:

 print(NameError("Your input was not recognized as a function, variable or  datatype"))

然后它会打印错误,但不会完全打印出来,也不是红色,像这样: Your input was not recognized as a function, variable or datatype

有没有办法使程序不退出并显示真正的错误?

3 个答案:

答案 0 :(得分:1)

在没有更多详细信息的情况下,您可以尝试执行以下操作:

try:
    raise(NameError("Your input was not recognized as a function, variable or  datatype"))
except Exception as e:
    print(repr(e))

但是,这并不是应该使用异常的确切方式。

答案 1 :(得分:0)

我很惊讶没有人提到Python termcolor模块。用法很简单:

from termcolor import colored

Python 2:

print colored('hello', 'red'), colored('world', 'green')

或者在Python 3中:

print(colored('hello', 'red'), colored('world', 'green'))

伴随使用“ try-except”语句,因为毕竟,您可以通过在except子句中添加某些内容来引发异常而无需退出程序。

答案 2 :(得分:0)

经过长期研究,我找到了答案: 这不会引发错误,但是会在终端和外壳上同时显示彩色错误

  1. 通过点子安装CLINT
pip install clint
  1. 在Python中
import sys
try:
    sys.stdout.shell.write("Your input was not recognized as a variable, function or datatype\n", "COMMENT")
except AttributeError:
    puts(colored.red("Your input was not recognized as a variable, function or datatype"))